On Thu, May 27, 2021 at 6:41 AM Steven Penny <srp...@gmail.com> wrote: > > If I want to scan through a string, I can do this: > > ~~~go > package main > > import ( > "fmt" > "strings" > ) > > func main() { > r := strings.NewReader("west north east") > for { > var s string > _, e := fmt.Fscan(r, &s) > fmt.Printf("%q %v\n", s, e) > if e != nil { break } > } > } > ~~~ > > Result: > > ~~~ > "west" <nil> > "north" <nil> > "east" <nil> > "" EOF > ~~~ > > I recently discovered `fmt.Scanner` [1], so I thought I would try to > implement it. I came up with this: > > ~~~go > package main > > import ( > "fmt" > "strings" > ) > > type comma struct { tok string } > > func (c *comma) Scan(s fmt.ScanState, r rune) error { > tok, err := s.Token(false, func(r rune) bool { > return r != ',' > }) > if err != nil { > return err > } > c.tok = string(tok) > if _, _, err := s.ReadRune(); err != nil { > return err > } > return nil > } > > func main() { > r := strings.NewReader("west,north,east") > for { > var c comma > _, e := fmt.Fscan(r, &c) > fmt.Printf("%q %v\n", c.tok, e) > if e != nil { break } > } > } > ~~~ > > Result: > > ~~~ > "west" <nil> > "north" <nil> > "east" unexpected EOF > ~~~ > > So the result is pretty similar, but what bothers me is the `unexpected EOF`. > It seems it is due to this code: > > https://github.com/golang/go/blob/3075ffc93e962792ddf43b2a528ef19b1577ffb7/src/fmt/scan.go#L956-L966 > > It seems like `EOF` should be valid in this case, or perhaps I dont > understand the reasoning for it to be unexpected.
If you want to use fmt.Scanner, the Scan method of the types you are using should not return an acceptable io.EOF. That doesn't make sense as an error from a Scan method. A Scan method that encounters io.EOF at the end of valid input should store the valid result and return nil. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUP4B_j%2BcGTdOWb5hTNQ892_FoEvV1g9u4C_4TsqwBnvA%40mail.gmail.com.