为什么运行时错误io.WriterString? [英] why runtime error on io.WriterString?
问题描述
运行以下代码时,出现panic:运行时错误:无效的内存地址或零指针取消引用。我不明白为什么,并且似乎无法从io.WriteString(w,s)中发现我认为问题存在的错误。任何人都可以指引我正确的方向吗?
包主
$ b导入(
io
fmt
$ b $ func main(){
s:=hei
var w io.Writer
_,err:= io.WriteString(w ,s)
if err!= nil {
fmt.Println(s)
}
}
如果您添加
fmt .Println(w)
紧随 var w io.Writer
,你会看到打印的内容是< nil>
。这意味着你只是创建一个变量,而不是将其初始化为一个实际值。然后你试图将它传递给一个需要一个真正的 io.Writer
对象的函数,但是会得到一个零。
此外, io.Writer
是一个界面(请参阅 http ://golang.org/pkg/io/#Writer ),所以你需要找到它的具体实现(比如 os.Stdout
)到能够实例化它。
有关 io
包的更多信息,请参阅 http://golang.org/pkg/io/ 。
PS 也许你会将此与C ++混淆;在C ++中,当您执行 io :: Writer w
时, io :: Writer
,然而,Go代码 var w io.Writer
实际上相当于 io :: Writer * w
在C ++中,很显然在这种情况下 w
将包含 null
或更可能是一些不确定的垃圾。 (Go确保它是 null
)。
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).
这篇关于为什么运行时错误io.WriterString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!