Golang bufio.ReadSlice() function example

package bufio

ReadSlice reads until the first occurrence of delimiter in the input, returning a slice pointing at the bytes in the buffer. The bytes stop being valid at the next read. If ReadSlice encounters an error before finding a delimiter, it returns all the data in the buffer and the error itself (often io.EOF). ReadSlice fails with error ErrBufferFull if the buffer fills without a delimiter. Because the data returned from ReadSlice will be overwritten by the next I/O operation, most clients should use ReadBytes or ReadString instead. ReadSlice returns err != nil if and only if line does not end in delimiter.

Golang bufio.ReadSlice() function usage example

 readbuffer := bytes.NewBuffer([]byte("abcde#fghijk"))

 reader := bufio.NewReader(readbuffer)

 front,_ := reader.ReadSlice('#') // # is the delimiter

 fmt.Println(string(front))

 reader.ReadSlice('#') // will read the remainder

 fmt.Println(string(front))

Output :

abcde#

fghijk

Advertisement