0

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)
}
0

1 Answer 1

5

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().

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your helping and teaching something new, TypeAssertion. I'd go for it since I have to make a queue like structure so list is apt.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.