duandao3265 2015-01-13 08:57
浏览 10
已采纳

开始-获取父结构

I'd like to know how to retrieve the parent struct of an instance.
I have no idea how to implement this.

For instance:

type Hood struct {
    name string
    houses  []House
}

type House struct {
    name   string
    people int16
}

func (h *Hood) addHouse(house House) []House {
    h.houses = append(h.houses, house)
    return h.houses
}

func (house *House) GetHood() Hood {
    //Get hood where the house is situated
    return ...?
}

Cheers

  • 写回答

1条回答 默认 最新

  • donglu0494 2015-01-13 09:02
    关注

    You should retain a pointer to the hood.

    type House struct {
        hood   *Hood
        name   string
        people int16
    }
    

    and when you append the house

    func (h *Hood) addHouse(house House) []House {
        house.hood = h
        h.houses = append(h.houses, house)
        return h.houses
    }
    

    then you can easily change the GetHood, although a getter may not be required at that point.

    func (house *House) GetHood() Hood {
        return *house.hood
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀
  • ¥15 mifare plus卡认证
  • ¥30 LSTM预测结果是一条直线
  • ¥15 stnodeeditor自定义控件
  • ¥15 SDO如何更改STM32的波特率
  • ¥15 uniapp的uni-datetime-picker组件在ios端不适配
  • ¥15 前端 uniapp App端在离线状态如何使用modbus 连接手机蓝牙进行读写操控机器?