dsyua2828 2015-03-10 15:48
浏览 60
已采纳

从非指针结构元素转到链接列表指针分配

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.

Here's the code that works: http://play.golang.org/p/P9FjK8A-32 which is same as Go's original container/list code

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?

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

Why am I getting this error? Why does Go define root as a non-pointer value when it defines next, and prev as pointers?

Thanks

  • 写回答

1条回答 默认 最新

  • dongsuiying7773 2015-03-10 15:57
    关注

    A pointer is nil by default and needs to be initialized.

    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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?