dongmu1996
dongmu1996
2013-10-05 10:21

为什么io.WriterString出现运行时错误?

  • io
已采纳

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)
    }   
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duankuaiwang2706 duankuaiwang2706 8年前

    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).

    点赞 评论 复制链接分享
  • dongyingla8668 dongyingla8668 8年前
    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
    
    点赞 评论 复制链接分享