dq23171 2012-10-27 15:02
浏览 41
已采纳

在地图的结构上调用指针方法

There is the type Company, which is a struct, containing a map of Person's, which are also all structs.

type Company struct {
    employees map[int]Person
}

type Person struct {
    [...]
}

After allocating some Person's to the employees-map, I'm trying to call a pointer method on each of these.

func (company *Company) Populate(names []string) {
    for i := 1; i <= 15; i++ {
        company.employees[i] = Person{names[i - 1], [...]}
        company.employees[i].Initialize()
    }
}

This miserably fails, with the go-Compiler complaining that I can't call pointer methods on company.employees[i], as well as I can't take the address of company.employees[i]. However, setting the Initialize-method to a non-pointer method and letting it return the copy of the person, and allocating it to the map again by using

company.employees[i] = company.employees[i].Initialize()

works, which is not that different.

Not having worked with pointers ever this bugs me quite much. Map's aren't immutable, and they get modified either way, so calling a pointer method on an entity in a map shouldn't be a problem - atleast in my head.

If anyone could explain to me what I'm doing wrong here - or correct my thinking - I'd be pleased.

  • 写回答

2条回答 默认 最新

  • douyangquan2474 2012-10-27 15:41
    关注

    The problem here is that in order to call a pointer method, the address of employees[i] needs to be taken. According to the Go specification:

    The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a composite literal.

    A map indexing operation is not addressable. This was decided so that map implementations would not need to guarantee that the addresses of values would not change. As more data is added to the map, it may relocate data for efficiency reasons.

    So, how can you fix it? If you have a map[int]*Person, you will not need to take the address of the data in the map since the map value is already an address.

    One last bit of advice, Person.Initialize() is not very idiomatic Go code. If you need to initialize a type, you normally use a NewPerson() function. The NewPerson() function would return an initialized Person struct or pointer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab