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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With