12

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
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Mike
  • 7,769
  • 13
  • 57
  • 81

2 Answers2

14

You can do this with a bufio.Scanner
Godoc at http://golang.org/pkg/bufio/#Scanner

Something like this:

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

A full example here: http://play.golang.org/p/xrFEGF3h5P

fredrik
  • 13,282
  • 4
  • 35
  • 52
8

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".

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Definitely recommend using a string reader vs strings.Split. Splitting can leave you with unwanted characters such as \r on the end of your strings depending on your environment – Jaybeecave May 16 '17 at 10:00