package main import ( "bytes" "fmt" "os" ) func main() { file, err := os.Open("example.txt") if err != nil { fmt.Println(err) return } defer file.Close() buffer := bytes.Buffer{} bytesWritten, err := buffer.ReadFrom(file) if err != nil { fmt.Println(err) return } fmt.Println("Bytes read:", bytesWritten) fmt.Println("Contents of buffer:", buffer.String()) }
package main import ( "bytes" "fmt" "strings" ) func main() { str := "This is a test string" reader := strings.NewReader(str) buffer := bytes.Buffer{} bytesWritten, err := buffer.ReadFrom(reader) if err != nil { fmt.Println(err) return } fmt.Println("Bytes read:", bytesWritten) fmt.Println("Contents of buffer:", buffer.String()) }In this example, we use a `strings.Reader` to read from a string and write its contents to a bytes.Buffer using the `ReadFrom` method. We then print out the number of bytes read and the contents of the buffer. Overall, the bytes.Buffer ReadFrom method is a useful tool for reading data from various sources and writing it into a buffer for processing. It is a part of the bytes package in the standard library of the Go programming language.