go - Why am I getting an never ending loop when reading from a byte.Buffer -


currently i'm writing program reading buffer bytes.buffer. supposed stop reading when finds character e. when reading buffer using loop noticed odd. when put byte reading part of statement infinity loop (example in go playground):

b := bytes.newbuffer([]byte("uoiea")) v, _ := b.readbyte(); v != 'e'; {     println("the value " + string(v)) } 

but if removed , put inside loop, doesn't (example in go playground):

b := bytes.newbuffer([]byte("uoiea")) ;; {     v, _ := b.readbyte()     println("the value " + string(v))     if v == 'e'{         break     } } 

does know why this? find adding break expression ugly , error prone way solve this.

because post statement of for-loop empty (you have init statement), don't read next byte every iteration (v 'u').

here fixed version:

b := bytes.newbuffer([]byte("uoiea")) v, _ := b.readbyte(); v != 'e'; v, _ = b.readbyte() {     println("the value " + string(v)) } 

as mentioned in comments, it's recommended check error avoid infinite loop when there no 'e' byte:

b := bytes.newbuffer([]byte("uoiea")) v, e := b.readbyte(); v != 'e' && e == nil; v, e = b.readbyte() {     println("the value " + string(v)) } 

readbytes returns io.eof error when buffer empty.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -