获取父结构体

huangapple go评论79阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2015年1月13日 16:57:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/27918208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定