I can't get my head around type casting using interfaces.
There is an example for setting value using pointers:
func main() {
a := &A{}
cast(a, "BBB")
fmt.Println(a.s)
}
type A struct {
s string
}
func cast(a *A, b interface{}) {
a.s = b.(string)
}
The output of this program will print BBB
.
Now my problem is that what if I want to set more than string? I imagine that I want to do something like this:
func main() {
a := &A{}
cast(&(a.s), "BBB")
fmt.Println(a.s)
}
type A struct {
s string
}
func cast(a interface{}, b interface{}) {
// Here could be type switch to determine what kind of type I want to cast to, but for know string is enough...
a = b.(string)
}
And this code's output is an empty string... Could anyone help me to understand what I've been doing wrong?
CodePudding user response:
The second program assigns to local variable a
, not to the caller's variable a
.
You must dereference the pointer to assign to the caller's value. To do, that you need a pointer type. Use a type assertion to get the pointer type:
func cast(a interface{}, b interface{}) {
*a.(*string) = b.(string)
}