Go - get parent struct

怎甘沉沦 提交于 2019-12-11 03:03:56

问题


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:


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
}


来源:https://stackoverflow.com/questions/27918208/go-get-parent-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!