Go: split byte.Buffer by newline

Pretty new to Go and running into a problem like:

var metrics bytes.Buffer

metrics.WriteString("foo")
metrics.WriteString("\n")

metrics.WriteString("bar")
metrics.WriteString("\n")

      

Now I want to iterate over these metrics and split on a new line. I tried

for m := strings.Split(metrics.String(), "\n") {
     log.Printf("metric: %s", m)
}

      

but i get the following

./relay.go:71: m := strings.Split(metrics.String(), "\n") used as value

      

+3


source to share


2 answers


Considering what an strings.Split()

array returns it would be easier to use a range

m := strings.Split(metrics.String(), "\n")
for _, m := range strings.Split(metrics.String(), "\n") {
    log.Printf("metric: %s", m)
}

      

Note. To read lines from a string, you might consider " go readline -> string ":

bufio.ReadLine()

or better: bufio.Scanner



How in:

const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
scanner := bufio.NewScanner(strings.NewReader(input))

      

For more information, see Scanner shuts down earlier .

+4


source


You can do this with bufio.Scanner


Godoc at http://golang.org/pkg/bufio/#Scanner

Something like that:



var metrics bytes.Buffer

metrics.WriteString("foo")
metrics.WriteString("\n")

metrics.WriteString("bar")
metrics.WriteString("\n")

scanner := bufio.NewScanner(&metrics)
for scanner.Scan() {
    log.Printf("metric: %s", scanner.Text())
}

if err := scanner.Err(); err != nil {
    log.Fatal(err)
}

      

Full example here: http://play.golang.org/p/xrFEGF3h5P

+8


source







All Articles