I am scratching my head over an unexpected difference between having my struct contain list.List vs *list.List. Why doesn't the following work?
type listHolder struct {
id int
mylist list.List
}
func newListHolder(id int, text string) listHolder {
var newLH listHolder
newLH.mylist = *list.New()
newLH.id = id
newLH.mylist.PushBack(text)
return newLH
}
func (l *listHolder) pushBack(text string) {
l.mylist.PushBack(text)
}
func (l *listHolder) printAll() {
for temp := l.mylist.Front(); temp != nil; temp = temp.Next() {
fmt.Println(temp.Value)
}
}
func main() {
a := newListHolder(1, "first")
a.pushBack("second")
fmt.Printf("listHolder %d length %d Front()= %v, Back()=%v
",
a.id, a.mylist.Len(), a.mylist.Front().Value, a.mylist.Back().Value)
a.printAll()
}
This outputs the following, showing that the length is as expected but the Front() and Back() methods don't work.
listHolder 1 length 2 Front()= `<nil>`, Back()=<nil>
<nil>
If I define the struct as
// Same thing with a pointer
type listHolderPtr struct {
id int
mylist *list.List
}
func newListHolderPtr(id int, text string) listHolderPtr {
var newLH listHolderPtr
newLH.mylist = list.New()
newLH.id = id
newLH.mylist.PushBack(text)
return newLH
}
that works as expected, but of course, any copies of the listHolder struct share a reference to the same list, which is not what I want. I need to be able to copy the surrounding object and get a new copy of the internal list. Is that possible?
See https://play.golang.org/p/KCtTwuvaS1R for a simplified example of what I'm trying to do. In the real use case, I'll be pushing onto the back and popping off the front of each listHolder in a slice of listHolder in a complicated nested loop.