英文:
GO type cast and assignment using interfaces
问题
我无法理解使用接口进行类型转换的问题。
这里有一个使用指针设置值的示例:
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)
}
这个程序的输出将打印BBB
。
现在我的问题是,如果我想设置的不仅仅是字符串,该怎么办?我想象中的代码是这样的:
func main() {
a := &A{}
cast(&(a.s), "BBB")
fmt.Println(a.s)
}
type A struct {
s string
}
func cast(a interface{}, b interface{}) {
// 这里可以使用类型切换来确定我想要转换的类型,但目前只需要字符串就够了...
a = b.(string)
}
这段代码的输出是一个空字符串... 有人可以帮我理解我做错了什么吗?
英文:
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?
答案1
得分: 2
第二个程序将值赋给局部变量 a
,而不是调用者的变量 a
。
你必须解引用指针来赋值给调用者的值。为了做到这一点,你需要一个指针类型。使用类型断言来获取指针类型:
func cast(a interface{}, b interface{}) {
*a.(*string) = b.(string)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论