-1
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)```

fails with error sample.hd undefined (type *list.Element has no field or method hd)

  • While you can implement a queue using a list a slice may be more appropriate - see [this answer](https://stackoverflow.com/a/21328187/11810946) for more info. – Brits Feb 19 '21 at 19:27

1 Answers1

0

This is what you need

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

Your value "sample" is a list.Element, which is a struct containing some hidden fields related to the list structure, as well as a field Value, which is the actual data that you stored in it. Value is of type interface{}, so you need to do a type assertion to use your struct fields.

Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33
  • 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()) } fails with this error – Pulkit Kundra Feb 19 '21 at 20:06
  • panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x109e13d] – Pulkit Kundra Feb 19 '21 at 20:06