英文:
How do I convert a generic struct to the same generic struct of a different type in Golang?
问题
让我们直接看一段代码。
type Animal[T any] struct {
Name string
Type string
Params T
}
type DogParams struct {
TailLength int
}
type CatParams struct {
MeowVolume int
}
type Dog = Animal[DogParams]
type Cat = Animal[CatParams]
type Tiger = Animal[CatParams]
var animals = []Animal[any]{
{
Name: "biggie doggie",
Type: "dog",
Params: DogParams{TailLength: 5},
},
{
Name: "persia",
Type: "cat",
Params: CatParams{MeowVolume: 2},
},
}
将Animal[any]
转换为Animal[CatParams]
的最佳方法是什么?
我尝试了以下代码:
cat, ok := any(animals[1]).(Cat)
但是它不起作用。
提前感谢!
英文:
Lets jump straight into a code snippet.
type Animal[T any] struct {
Name string
Type string
Params T
}
type DogParams struct {
TailLength int
}
type CatParams struct {
MeowVolume int
}
type Dog = Animal[DogParams]
type Cat = Animal[CatParams]
type Tiger = Animal[CatParams]
var animals = []Animal[any]{
{
Name: "biggie doggie",
Type: "dog",
Params: DogParams{TailLength: 5},
},
{
Name: "persia",
Type: "cat",
Params: CatParams{MeowVolume: 2},
},
}
What is the best way to convert an animal from Animal[any]
to Animal[CatParams]
?
I have tried
cat, ok := any(animals[1]).(Cat)
and it's not ok.
Thanks in advance!
答案1
得分: 0
根据@Volker和@Pak Uula的评论,你可以将它们放入一个interface{}
切片中,但这并不是运行时动态类型。Cat
仍然是Cat
:
var animals = []interface{}{
Dog{
Name: "biggie doggie",
Type: "dog",
Params: DogParams{TailLength: 5},
},
Cat{
Name: "persia",
Type: "cat",
Params: CatParams{MeowVolume: 2},
},
}
英文:
Following the comments from @Volker and @Pak Uula, you can stick them in an interface{}
slice, but this isn't run-time dynamic typing. A Cat
is still a Cat
:
var animals = []interface{}{
Dog{
Name: "biggie doggie",
Type: "dog",
Params: DogParams{TailLength: 5},
},
Cat{
Name: "persia",
Type: "cat",
Params: CatParams{MeowVolume: 2},
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论