使用接口进行类型转换和赋值

Damon   2022-11-11T00:18:59

我无法理解使用接口进行类型转换。

有一个使用指针设置值的示例:

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)
}

这段代码的输出是一个空字符串......谁能帮我理解我做错了什么?

点击广告,支持我们为你提供更好的服务
评论(1)
Damon

第二个程序分配给局部变量a,而不是调用者的变量a

您必须取消引用指针以分配给调用者的值。为此,您需要一个指针类型。使用类型断言来获取指针类型:

func cast(a interface{}, b interface{}) {
    *a.(*string) = b.(string)
}
2022-11-11T00:18:59   回复