【问题标题】:how to make queue of type struct in golang如何在golang中制作struct类型的队列
【发布时间】:2021-02-19 19:04:14
【问题描述】:
type top struct {
    node *tree
    hd   int
}

func (t *bt) topview() {
    if t.root == nil {
        return
    }
    qu := list.New()
    qu.PushBack(top{t.root, 0})
    sample := qu.Front()
    fmt.Println(sample.hd)```

失败,错误 sample.hd undefined (type *list.Element has no field or method hd)

【问题讨论】:

  • 虽然您可以使用列表实现队列,但切片可能更合适 - 请参阅 this answer 了解更多信息。

标签: go queue


【解决方案1】:

这就是你需要的

fmt.Println(sample.Value.(top).hd)

你的值“sample”是一个list.Element,它是一个包含一些与列表结构相关的隐藏字段的结构,以及一个字段Value,这是你存储在其中的实际数据。 Valueinterface{} 类型,所以你需要做一个 type assertion 来使用你的结构字段。

【讨论】:

  • for qu != nil { sample := qu.Front() for key := range topview { if key != sample.Value.(top).hd { topview[sample.Value.( top).hd] = sample.Value.(top).node } } if sample.Value.(top).node.left != nil { qu.PushBack(top{sample.Value.(top).node.left , sample.Value.(top).hd - 1}) } if sample.Value.(top).node.right != nil { qu.PushBack(top{sample.Value.(top).node.right, sample .Value.(top).hd + 1}) } qu.Remove(qu.Front()) } 失败并出现此错误
  • 恐慌:运行时错误:无效的内存地址或 nil 指针取消引用 [信号 SIGSEGV:分段违规代码=0x1 addr=0x10 pc=0x109e13d]
猜你喜欢
  • 1970-01-01
  • 2019-10-10
  • 2019-04-23
  • 2016-10-20
  • 2018-02-18
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多