Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
Problem :
You created a variable of type bytes.Buffer and encounter this error message when you want to use the variable with bufio.NewWriter() function.
cannot use buffer (type bytes.Buffer) as type io.Writer in argument to bufio.NewWriter: bytes.Buffer does not implement io.Writer (Write method has pointer receiver)
Solution :
From https://golang.org/pkg/bufio/#NewWriter, the NewWriter() will return a pointer *Writer . i.e this explains part the of the error message - Write method has pointer receiver.
To fix this error, you need to provide the memory address of the buffer. In this code example below, you will see that bytes.NewBuffer(nil) is the same as &bytes.Buffer{} and os.Stdout is ok because the underlaying is a pointer of *File type.
package main
import (
"bufio"
"fmt"
"os"
"bytes"
)
func main() {
// redirect to screen, not an issue because os.Stdout is a pointer
screenWriter := bufio.NewWriter(os.Stdout)
fmt.Fprint(screenWriter, "Hello world! 你好世界!\n")
screenWriter.Flush() // Don't forget to flush!
// redirect to buffer
//var buffer bytes.Buffer
//bufferWriter := bufio.NewWriter(buffer) // <--- not ok, will generate error message
//bufferWriter := bufio.NewWriter(&buffer) // <-- ok
buffer := bytes.NewBuffer(nil) // same as &bytes.Buffer{}, so it is ok as well.
bufferWriter := bufio.NewWriter(buffer)
bufferWriter.Flush() // Don't forget to flush!
}
References :
https://www.socketloop.com/references/golang-bufio-newwriter-function-example
See also : Golang : Reset buffer example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.6k Golang : Convert(cast) uintptr to string example
+6k Unix/Linux : Use netstat to find out IP addresses served by your website server
+20.7k Golang : Create and resolve(read) symbolic links
+6.9k Golang : File system scanning
+6.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+5k PHP : Hide PHP version information from curl
+11.8k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+18.2k Golang : Set, Get and List environment variables
+9.6k Golang : Translate language with language package example
+4.9k Golang : The Tao of importing package
+6.2k Golang : Totalize or add-up an array or slice example
+11.6k Golang : Save webcamera frames to video file