将golang中的struct[int]转换为struct[any]。

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

Covert struct[int] to struct[any] in golang

问题

在Golang中,无法直接将*A[int]转换为*A[any]。这是因为Golang中的泛型类型参数是不可变的,即使intany的子类型,也不能进行这种转换。

如果你想要实现这种转换,可以考虑使用接口来解决。你可以定义一个接口类型,然后让A[V]实现该接口。这样,你就可以将*A[int]转换为接口类型*A[any],然后将其传递给函数f

以下是一个示例代码:

type A[V any] struct {
	v V
}

type AnyA interface {
	GetV() interface{}
}

func (a *A[V]) GetV() interface{} {
	return a.v
}

func f(a AnyA) {
	// ...
}

a := &A[int]{v: 1}

f(a) // 不会报错

在上面的代码中,我们定义了一个AnyA接口,该接口包含一个GetV方法,返回类型为interface{}。然后,我们让A[V]实现了该接口,并在GetV方法中返回了a.v。最后,我们将a传递给函数f,不会再报错。

希望对你有帮助!如果还有其他问题,请随时提问。

英文:
type A[V any] struct {
  v V
}

func f(*A[any]) {
...
}

a := &A[int]{v: 1}

f(a) // error: cannot use a (variable of type *A[int]) as type *A[any] in argument to f

Is there a way that can convert *A[int] to *A[any] in Golang?

Please Help!

答案1

得分: 1

有没有办法在Golang中将A[int]转换为A[any]?

没有,Golang中没有这种语法或内置功能。

有没有办法在Golang中将A[int]转换为A[any]?

是的,可以编写一个函数来实现这个功能(对于每个切片元素)。

英文:

> Is there a way that can convert *A[int] to *A[any] in Golang?

No, there is no syntax or builtin for this stuff.

> Is there a way that can convert *A[int] to *A[any] in Golang?

Yes, write a function which does this (for each slice element).

答案2

得分: 0

不,你不能将 *A[int] 转换为 *A[any],除非使用一些不安全的指针转换。

但是你可以将函数 f 改为一个通用函数:

func f[V any](a *A[V]) {
	fmt.Println(a)
}
英文:

No, you cannot convert *A[int] to *A[any] without using some unsafe pointer conversions.

But you can change the function f to a generic function:

func f[V any](a *A[V]) {
	fmt.Println(a)
}

huangapple
  • 本文由 发表于 2022年8月2日 11:23:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73201653.html
匿名

发表评论

匿名网友

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

确定