Home > database >  Covert struct[int] to struct[any] in golang
Covert struct[int] to struct[any] in golang

Time:08-02

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!

CodePudding user response:

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

CodePudding user response:

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).

  •  Tags:  
  • go
  • Related