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

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

How do I convert a generic struct to the same generic struct of a different type in Golang?

问题

让我们直接看一段代码。

  1. type Animal[T any] struct {
  2. Name string
  3. Type string
  4. Params T
  5. }
  6. type DogParams struct {
  7. TailLength int
  8. }
  9. type CatParams struct {
  10. MeowVolume int
  11. }
  12. type Dog = Animal[DogParams]
  13. type Cat = Animal[CatParams]
  14. type Tiger = Animal[CatParams]
  15. var animals = []Animal[any]{
  16. {
  17. Name: "biggie doggie",
  18. Type: "dog",
  19. Params: DogParams{TailLength: 5},
  20. },
  21. {
  22. Name: "persia",
  23. Type: "cat",
  24. Params: CatParams{MeowVolume: 2},
  25. },
  26. }

Animal[any]转换为Animal[CatParams]的最佳方法是什么?

我尝试了以下代码:

  1. cat, ok := any(animals[1]).(Cat)

但是它不起作用。

提前感谢!

英文:

Lets jump straight into a code snippet.

  1. type Animal[T any] struct {
  2. Name string
  3. Type string
  4. Params T
  5. }
  6. type DogParams struct {
  7. TailLength int
  8. }
  9. type CatParams struct {
  10. MeowVolume int
  11. }
  12. type Dog = Animal[DogParams]
  13. type Cat = Animal[CatParams]
  14. type Tiger = Animal[CatParams]
  15. var animals = []Animal[any]{
  16. {
  17. Name: "biggie doggie",
  18. Type: "dog",
  19. Params: DogParams{TailLength: 5},
  20. },
  21. {
  22. Name: "persia",
  23. Type: "cat",
  24. Params: CatParams{MeowVolume: 2},
  25. },
  26. }

What is the best way to convert an animal from Animal[any] to Animal[CatParams] ?

I have tried

  1. cat, ok := any(animals[1]).(Cat)

and it's not ok.

Thanks in advance!

答案1

得分: 0

根据@Volker和@Pak Uula的评论,你可以将它们放入一个interface{}切片中,但这并不是运行时动态类型。Cat仍然是Cat

  1. var animals = []interface{}{
  2. Dog{
  3. Name: "biggie doggie",
  4. Type: "dog",
  5. Params: DogParams{TailLength: 5},
  6. },
  7. Cat{
  8. Name: "persia",
  9. Type: "cat",
  10. Params: CatParams{MeowVolume: 2},
  11. },
  12. }
英文:

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:

  1. var animals = []interface{}{
  2. Dog{
  3. Name: "biggie doggie",
  4. Type: "dog",
  5. Params: DogParams{TailLength: 5},
  6. },
  7. Cat{
  8. Name: "persia",
  9. Type: "cat",
  10. Params: CatParams{MeowVolume: 2},
  11. },
  12. }

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:

确定