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

huangapple go评论78阅读模式
英文:

why runtime error on io.WriterString?

问题

当运行以下代码时,我遇到了一个"panic: runtime error: invalid memory address or nil pointer dereference"错误。我不明白为什么会出现这个错误,也无法捕捉到我认为问题出在io.WriteString(w, s)的错误。有人能指点我正确的方向吗?

package main

import (
	"io"
	"fmt"
)

func main() {
	s := "hei"
	var w io.Writer
	_, err := io.WriteString(w, s)
	if err != nil {
		fmt.Println(s)
	}
}
英文:

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

答案1

得分: 6

如果你在 var w io.Writer 之后添加 fmt.Println(w),你会发现打印出来的是 <nil>。这意味着你只是创建了一个变量,但没有将其初始化为一个真实的值。然后你尝试将它传递给一个需要真实的 io.Writer 对象的函数,但实际上传递的是一个空值。

另外,io.Writer 是一个接口(参见 http://golang.org/pkg/io/#Writer),所以你需要找到一个具体的实现(比如 os.Stdout)来实例化它。

有关 io 包的更多信息,请参见 http://golang.org/pkg/io/

P.S. 也许你把它和 C++ 混淆了;在 C++ 中,当你写 io::Writer w 时,w 会自动初始化为一个包含 io::Writer 的新副本,然而,Go 代码中的 var w io.Writer 实际上等同于 C++ 中的 io::Writer* w,很明显,在这种情况下,w 将包含 null 或更可能是一些不确定的垃圾值。(不过 Go 保证它是 null)。

英文:

If you add

fmt.Println(w)

right after var w io.Writer, you'll see that what gets printed is &lt;nil&gt;. 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).

答案2

得分: 2

var w io.Writer

w初始化为nil写入器。你需要将它指向一个实际的写入器才能对其进行有用的操作,例如:

w = os.Stdout

英文:
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

huangapple
  • 本文由 发表于 2013年10月5日 18:21:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/19196653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定