dongmu1996 2013-10-05 10:21
浏览 58
已采纳

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

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 2013-10-05 10:29
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料