相关疑难解决方法(0)

隐藏零值,理解为什么golang在这里失败

我无法理解如何正确地确保nil在这种情况下不存在某些事情:

package main

type shower interface {
  getWater() []shower
}

type display struct {
  SubDisplay *display
}

func (d display) getWater() []shower {
  return []shower{display{}, d.SubDisplay}
}

func main() {
  // SubDisplay will be initialized with null
  s := display{}
  // water := []shower{nil}
  water := s.getWater()
  for _, x := range water {
    if x == nil {
      panic("everything ok, nil found")
    }

    //first iteration display{} is not nil and will
    //therefore work, on the second iteration …
Run Code Online (Sandbox Code Playgroud)

null pointers interface go

44
推荐指数
2
解决办法
1万
查看次数

标签 统计

go ×1

interface ×1

null ×1

pointers ×1