I came across working with the any
type. Everything worked quite well until I tried/had to work with a pointer to an any
(*any
). Here is an example playground link, the code is also at the bottom of this post.
In case I have a struct with a defined type, everything is fine. If I change it to any (not a pointer to it), calling the new method is also straightforward. Retrieving the actual value needs some casting, of course.
But as soon as I use a pointer to any
, I have to copy the variable to a var xyz any
and for the way back I need some helper variables, too.
Is there a better way to work with the dataThree
stuct and the according func newThree(v *any) dataThree {...
function, but still keep it an *any
? Would some kind of reflection help?
package main
import "fmt"
type Value struct {
value int
}
/**
* type as pointer
*/
type dataOne struct {
data *Value
}
func newOne(v *Value) dataOne {
return dataOne{
data: v,
}
}
/**
* Any as value
*/
type dataTwo struct {
data any
}
func newTwo(v Value) dataTwo {
return dataTwo{
data: v,
}
}
/**
* Any as pointer
*/
type dataThree struct {
data *any
}
func newThree(v *any) dataThree {
return dataThree{
data: v,
}
}
func main() {
one := Value{value: 1}
myOne := newOne(&one)
fmt.Println(myOne.data.value)
two := Value{value: 2}
myTwo := newTwo(two)
fmt.Println(myTwo.data.(Value).value)
three := Value{value: 3}
var aT any
aT = three
myThree := newThree(&aT)
myData := *myThree.data
castAt := myData.(Value)
fmt.Println(castAt.value)
}
2