Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: split byte.Buffer by newline

Tags:

go

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 cycle through that metrics and split by newline. 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
like image 765
Mike Avatar asked Nov 05 '14 20:11

Mike


1 Answers

Considering that strings.Split() returns an array, it would be easier to use 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 can consider "go readline -> string":

bufio.ReadLine() or better: bufio.Scanner

As 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))

See more at "Scanner terminating early".

like image 183
VonC Avatar answered Sep 17 '22 00:09

VonC