登录
首页 >  Golang >  Go问答

为什么不能直接在类型断言后为结构体字段赋值?

来源:stackoverflow

时间:2024-02-28 14:30:24 247浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《为什么不能直接在类型断言后为结构体字段赋值?》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

这是结构 bioperators。它实现了 myinterface1 (使用 bioperators 作为方法接收器)。这些只是一些测试代码,我在这里省略。

type bioperators struct {
    oprt1 float64
    oprt2 float64
}

我的问题是为什么我无法在类型断言后为 oprt1 赋值

func testTypeAssertion() {
    bio := BiOperators{111, 222}

    arr := []MyInterface1{bio, &bio}

    // I can do the conversion and output field oprt2
    fmt.Println((arr[0].(BiOperators)).oprt2)

    // But when I want to directly assign value to it, I got the following error
    // cannot assign to arr[0].(BiOperators).oprt2go

    // (arr[0].(BiOperators)).oprt2 = 99 <----this line is error

    // and I can't create a pointer to do the assignment
    // the following line has error : cannot take the address of arr[0].(BiOperators)go
    // bioCvt2 := &(arr[0].(BiOperators)) <----this line is error too

    // I can using the following lines to do the assignment. But it will create a new struct
    bioCvt := (arr[0].(BiOperators))

    bioCvt.oprt2 = 333

    fmt.Println("bioCvt", bioCvt)
    fmt.Println("arr[0](assigned using bio)", arr[0])

}

那么有没有办法在类型断言之后不创建一个新的结构来进行字段分配?


解决方案


当您将 bio 放入接口数组时,会生成 bio 的副本并将其存储在第零个元素中。第一个元素包含指向 bio 的指针,因此不会对该元素进行复制。同样,当您从接口转换回结构类型时,会创建该值的另一​​个副本。据推测,编译器或语言不允许这样做,因为您将修改一个无法再次访问以任何方式使用该值的副本。

即使使用上面的代码,类似的情况仍然会发生。当修改 biocvt 上的字段时,它根本不会修改 bio,因为您正在修改副本。

但是,如果将第一个元素转换为指针,则可以修改它,这是 bio 中的基础值:

func testTypeAssertion() {
    bio := BiOperators{111, 222}

    arr := []MyInterface1{bio, &bio}

    (arr[1].(*BiOperators)).oprt2 = 99 // does not error anymore

    fmt.Println("arr[1](assigned using bio)", arr[1])
    fmt.Println("bio", bio) // This will print 99
}

本篇关于《为什么不能直接在类型断言后为结构体字段赋值?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>