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 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?