【发布时间】:2021-11-27 07:34:55
【问题描述】:
我无法理解使用接口进行类型转换。
有一个使用指针设置值的例子:
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{}) {
// 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)
}
这段代码的输出是一个空字符串...谁能帮我理解我做错了什么?
【问题讨论】:
-
Go 没有强制转换功能。您指的是类型断言。
-
@gopher 对不起.. 我的错..