Is there a way to specify the type that goes into lists in Go?

Issue

Is there a way to specify the type that goes into lists in Go? I am new to Go and most of what I see from Google searches mentions slices and I even meant to ask this question. I am stuck with the code with lists and can’t modify to slices.

The documentation mentions that lists use an interface for the element.

I ask because I wrote this code:

a := list.New()
a.PushBack(x)

and got this error from the code that runs my file.

panic: interface conversion: interface {} is int, not fileA.TypeA

My hunch is to create a list that only accepts fileA.TypeA but am open to suggestions if there are other ways to fix this.

Solution

I guess when you’re reading data from list, you use wrong type to convert data.

For example.

package main

import (
    "container/list"
    "fmt"
)

type User struct {
    name string
}

func main() {
    l := list.New()
    l.PushBack(User{name: "Jack"})
    l.PushBack(2)

    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Println(e.Value.(int))
    }
}
// panic: interface conversion: interface {} is main.User, not int

The list have User & int two types, but if you only use int to convert all data in list, it’ll throw panic error. You need to use correct type to convert.

Then you could detect type like following example.

package main

import (
    "container/list"
    "fmt"
)

type User struct {
    name string
}

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("This type is int: %d", v)
    case User:
        fmt.Printf("This is User type: %#v\n", v)
    default:
        fmt.Printf("I don't know about type %T!\n", v)
    }
}

func main() {
    l := list.New()
    l.PushBack(User{name: "Jack"})
    l.PushBack(2)
    l.PushBack(3)

    for e := l.Front(); e != nil; e = e.Next() {
        do(e.Value)
    }
}

Answered By – Jack Yu

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.