使用接口进行 GO 类型转换和赋值
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{}) {
// 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)
}
这段代码的输出是一个空字符串...谁能帮助我理解我做错了什么?
第二个程序赋值给局部变量a
,而不是调用者的变量a
。
您必须取消引用指针以分配给调用者的值。为此,您需要一个指针类型。使用类型断言获取指针类型:
func cast(a interface{}, b interface{}) {
*a.(*string) = b.(string)
}
我无法理解使用接口进行类型转换。
有一个使用指针设置值的例子:
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)
}
这段代码的输出是一个空字符串...谁能帮助我理解我做错了什么?
第二个程序赋值给局部变量a
,而不是调用者的变量a
。
您必须取消引用指针以分配给调用者的值。为此,您需要一个指针类型。使用类型断言获取指针类型:
func cast(a interface{}, b interface{}) {
*a.(*string) = b.(string)
}