简体   繁体   English

Golang结构字段与切片语义:“具有”结构切片与“是”结构切片

[英]Golang struct field vs slice semantics: “has a” slice of structs vs “is a” slice of structs

I have the following struct representing a Webpage 我有以下表示网页的结构

type Webpage struct {
    url.URL
    references []url.URL
}

I want to represent a website as a collection of Webpages. 我想将网站表示为网页的集合。 I am using this struct, but it does not feel like what I am looking for: 我正在使用此结构,但感觉不像我在寻找什么:

type website struct {
    []Webpage
}

I read this as "a website has a slice of Webpages". 我将其读为“一个网站包含一部分网页”。 I want a type that represents "a website is a slice of Webpages". 我想要一个表示“网站网页的一部分”的类型。

What type do I use to represent the is relationship instead of the has relationship of a struct field? 我用什么类型来表示is关系而不是struct字段的has关系?

type Website []Webpage

WebsiteWebpage

Of course that's possible. 当然可以。 Your structs should be like this. 您的结构应该是这样的。

type Webpage struct {
  url        url.URL
  references []url.URL
}

type Website struct {
  webpages []Webpage
}

So the Website will contain a slice of Webpages . 因此,该Website将包含一部分Webpages This is common concept while handling with database. 这是在处理数据库时的常见概念。 If you want to take more example and learn more about the concept you may take a look to this GORM Documentation 如果您想举更多的例子并了解有关该概念的更多信息,请阅读此GORM文档。

Hope it helps. 希望能帮助到你。

Edit: 编辑:
On the book that you follow, there already provided example: https://www.golang-book.com/books/intro/9#section3 在您遵循的书上,已经提供了示例: https : //www.golang-book.com/books/intro/9#section3

type MultiShape struct {
    shapes []Shape
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM