[英]Go linked list pointer assignment from non-pointer struct element
https://github.com/golang/go/blob/master/src/container/list/list.go#L49 https://github.com/golang/go/blob/master/src/container/list/list.go#L49
I am having hard time why I am getting cannot assign to pointer
error in Go. 我很难理解为什么我
cannot assign to pointer
在Go中cannot assign to pointer
错误。
Here's the code that works: http://play.golang.org/p/P9FjK8A-32 which is same as Go's original container/list code 这是有效的代码: http : //play.golang.org/p/P9FjK8A-32 ,与Go的原始容器/列表代码相同
type List struct {
root Element
len int
}
type Element struct {
next, prev *Element
list *List
Value interface{}
}
The original code has root
as a value and reference it everytime it needs to be in pointer type but why not at first place define root
as a pointer? 原始代码将
root
作为值,并在每次需要使用指针类型时都引用它,但为什么不首先将root
定义为指针呢?
type List struct {
root *Element
len int
}
type Element struct {
next, prev *Element
list *List
Value interface{}
}
This give me an error: http://play.golang.org/p/1gCAR_rcx1 -> invalid memory address or nil pointer dereference
这给我一个错误: http : //play.golang.org/p/1gCAR_rcx1- >
invalid memory address or nil pointer dereference
Why am I getting this error? 为什么会出现此错误? Why does Go define
root
as a non-pointer value when it defines next
, and prev
as pointers? 为什么Go在将
next
和prev
定义为指针时将root
定义为非指针值?
Thanks 谢谢
A pointer is nil
by default and needs to be initialized. 指针默认为
nil
,需要初始化。
This: 这个:
// Init initializes or clears list l.
func (l *List) Init() *List {
l.root.next = l.root
l.root.prev = l.root
l.len = 0
return l
}
should become this: 应该变成这个:
// Init initializes or clears list l.
func (l *List) Init() *List {
l.root = new(Element) // necessary to avoid dereferencing a nil pointer
l.root.next = l.root
l.root.prev = l.root
l.len = 0
return l
}
Demo at http://play.golang.org/p/EYSscTMYnn 演示在http://play.golang.org/p/EYSscTMYnn
In the case of the standard library, it is not necessary to have root
be a pointer, however, for prev
and next
it is necessary, otherwise the struct definition would be recursive, which is not allowed, because it would in theory cause a struct of infinite size... 对于标准库,没有必要让
root
成为指针,但是,对于prev
和next
则是必须的,否则struct定义将是递归的,这是不允许的,因为从理论上讲它将导致struct无限大小...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.