Reputation: 14978
I am inserting a struct
variable in the list. I am able to retrieve that inserted item in the loop but not the individual value. I am getting the error:
e.Value.name undefined (type interface {} is interface with no methods)
Code given below:
type Item struct {
name string
value string
}
queue := list.New()
per := Item{name: "name", value: "Adnan"}
queue.PushFront(per)
for e := queue.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value.name)
}
Upvotes: 0
Views: 63
Reputation: 417402
container/list.List
is not generic, it works with interface{}
. Try to use a slice of type []*Item
or []Item
, so you won't have this problem.
If you must use list.List
, you may use a type assertion:
fmt.Println(e.Value.(Item).name)
Using a slice it could look like this:
var queue []Item
per := Item{name: "name", value: "Adnan"}
queue = append(queue, per)
for _, v := range queue {
fmt.Println(v.name)
}
Note however that append()
appends to the end of the slice, so it's not equivalent with List.PushFront()
.
Upvotes: 5