英文:
Go - get parent struct
问题
我想知道如何获取实例的父结构体。
我不知道如何实现这个。
例如:
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 {
// 获取房屋所在的社区
return ...?
}
干杯
英文:
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
得分: 12
你应该保留指向街区的指针。
type House struct {
hood *Hood
name string
people int16
}
当你添加房屋时,
func (h *Hood) addHouse(house House) []House {
house.hood = h
h.houses = append(h.houses, house)
return h.houses
}
然后你可以轻松地更改GetHood
,尽管此时可能不需要getter。
func (house *House) GetHood() Hood {
return *house.hood
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论