如何在Golang中将一个通用的结构体转换为不同类型的相同通用结构体?

huangapple go评论81阅读模式
英文:

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},
    },
}

huangapple
  • 本文由 发表于 2022年10月17日 12:37:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/74092637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定