英文:
Is there a way to specify the type that goes into lists in Go?
问题
在Go语言中,可以通过指定列表中的类型来实现。你提到你在Google搜索中看到了关于切片(slices)的内容,但是你现在却使用列表(list)并且无法修改为切片。根据Go语言文档的说明,列表使用一个接口(interface)来表示元素。
根据你提供的代码和错误信息,你的代码中出现了类型转换错误。你的猜测是创建一个只接受fileA.TypeA
类型的列表,这是一个不错的想法。你可以尝试使用自定义的列表类型,其中元素类型为fileA.TypeA
,以确保只接受该类型的元素。
希望这能帮助到你!如果有其他问题,请随时提问。
英文:
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.
答案1
得分: 1
我猜当你从列表中读取数据时,你使用了错误的类型来转换数据。
例如。
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
列表中有User和int两种类型,但是如果你只使用int来转换列表中的所有数据,它会抛出panic错误。你需要使用正确的类型进行转换。
然后你可以像下面的例子一样检测类型。
package main
import (
"container/list"
"fmt"
)
type User struct {
name string
}
func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("这个类型是int:%d\n", v)
case User:
fmt.Printf("这是User类型:%#v\n", v)
default:
fmt.Printf("我不知道这个类型:%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)
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论