I get a "panic: runtime error: invalid memory address or nil pointer dereference" when running the following code. I do not understand why and cant seem to catch the error from the io.WriteString(w, s) where I believe the problem resides. Can anybody point me in the right direction?
package main
import(
"io"
"fmt"
)
func main() {
s := "hei"
var w io.Writer
_, err := io.WriteString(w, s)
if err != nil{
fmt.Println(s)
}
}
If you add
fmt.Println(w)
right after var w io.Writer
, you'll see that what gets printed is <nil>
. This means you're just creating a variable but not initializing it to a real value. You then attempt to pass it to a function that needs a real io.Writer
object but gets a nil.
Also, io.Writer
is an interface (see http://golang.org/pkg/io/#Writer), so you need to find a concrete implementation of it (such as os.Stdout
) to be able to instantiate it.
For more information about the io
package, see http://golang.org/pkg/io/.
P.S. perhaps you're confusing this with C++; in C++, when you do io::Writer w
, then w
automatically gets initialized to contain a fresh copy of io::Writer
, however, the Go code var w io.Writer
is really equivalent to io::Writer* w
in C++, and it's obvious that w
in that case will contain null
or more probably some indeterministic garbage. (Go guarantees that it's null
though).
var w io.Writer
initializes w
to a nil
writer. You need to point it to an actual writer to do anything useful with it, e.g.
w = os.Stdout