package main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Open("example.txt") if err != nil { fmt.Println("Error:", err) return } defer file.Close() reader := bufio.NewReader(file) buffer := make([]byte, 20) n, err := reader.Read(buffer) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Read %d bytes: %s\n", n, buffer[:n]) }
package main import ( "bufio" "fmt" "strings" ) func main() { input := "foo\nbar\nbaz\n" reader := bufio.NewReader(strings.NewReader(input)) for { line, err := reader.ReadString('\n') if err != nil { break } fmt.Print(line) } }In this example, we use `bufio.NewReader` to read a string into a buffered reader. We then use a loop to read each line of the string using `reader.ReadString('\n')`, and print it to the console. The loop ends when `reader.ReadString` returns an error.