【问题标题】:GO type cast and assignment using interfaces使用接口进行类型转换和赋值
【发布时间】: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 对不起.. 我的错..

标签: go pointers casting


【解决方案1】:

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

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

func cast(a interface{}, b interface{}) {
    *a.(*string) = b.(string)
}

【讨论】:

    猜你喜欢
    • 2020-06-07
    • 2016-05-16
    • 2020-04-19
    • 2014-10-09
    • 2022-08-19
    • 1970-01-01
    • 2021-05-24
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多