doudun2212 2018-09-30 02:25
浏览 8
已采纳

在结构内部更改结构的引用

I've been trying to update a map variable inside a struct but with no luck.

I expected that maps in Golang are passed by reference and hence assigning one reference to another should work but that's not the case.

I might be missing something obvious here, and if that's the case, apologies!

package main

import (
        "fmt"
)

type Foo struct {
        t map[string]interface{}
}

func (F Foo) Set(ta map[string]interface{}) {
        F.t = ta
}
func (F Foo) Get() map[string]interface{} {
        return F.t
}

func main() {
        t := make(map[string]interface{})
        t["t"] = "sf"
        t["array"] = []int{1, 2, 3}

        fmt.Println(t) // prints map[t:sf array:[1 2 3]]
        var f Foo

        f.Set(t)
        // why the following?
        fmt.Println(f.t) //prints map[]

        f.t = t
        fmt.Println(f.t) //prints map[t:sf array:[1 2 3]]
}

Playground: https://play.golang.org/p/i1ESV1BdjGQ

  • 写回答

1条回答 默认 最新

  • douliang1369 2018-09-30 02:31
    关注

    Basically, you need a pointer receiver on your Set method to be able to change the state of your structure.

    Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are more common than value receivers.

    Get should also have a pointer receiver for consistency:

    Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

    See a tour of go for more examples.

    Here is a fix of your code:

    package main
    
    import (
        "fmt"
    )
    
    type Foo struct {
        t map[string]interface{}
    }
    
    func (F *Foo) Set(ta map[string]interface{}) {
        F.t = ta
    }
    func (F *Foo) Get() map[string]interface{} {
        return F.t
    }
    
    func main() {
        t := make(map[string]interface{})
        t["t"] = "sf"
        t["array"] = []int{1, 2, 3}
    
        fmt.Println(t)
        var f Foo
    
        f.Set(t)
        fmt.Println(f.Get()) //prints map[t:sf array:[1 2 3]]
    
        f.t = t
        fmt.Println(f.Get()) //prints map[t:sf array:[1 2 3]]
    }
    

    Outputs

    map[t:sf array:[1 2 3]]
    map[t:sf array:[1 2 3]]
    map[t:sf array:[1 2 3]]
    

    Try it yourself here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C