This question already has an answer here:
I want parse []string
values into particular types (e.g. int, float etc), so I must use different parse functions for different lines. My code:
value, err := strconv.Atoi(line[1])
value1, err := strconv.ParseFloat(line[4], 6)
value2, err := strconv.ParseFloat(line[5], 6)
value3, err := strconv.Atoi(line[2])
I must be sure that every value was parsed so for every value I must have err != nil
. Is there any approach to make it with one common error without
if err != nil {
return
}
after each line?
</div>
You can use fmt.Sscanf do do this with one error check:
package main
import (
"fmt"
)
func main() {
var i int
var j float64
var k int
if _, err := fmt.Sscanf("1,3.14,5", "%d,%f,%d", &i, &j, &k); err != nil {
panic(err)
}
fmt.Println(i, j, k)
}
You'll need to join the lines with some separator but that's trivial.
Also, there's a discussion about making handling of multiple errors nicer for Go 2, I'm not sure what the status of it is at the moment, but you can read about it here: https://go.googlesource.com/proposal/+/master/design/go2draft-error-handling-overview.md