登录
首页 >  Golang >  Go问答

在 Golang 中,是否需要为每个用例创建独立的结构体?

来源:stackoverflow

时间:2024-02-06 12:42:16 402浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《在 Golang 中,是否需要为每个用例创建独立的结构体?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在使用 golang 为我的博客构建一个简单的 rest api。我将我的帖子存储在 mongodb 中,因此,当我检索某些记录时,我必须序列化(不确定这是否是一个正确的术语)到本机 golang 类型(结构)。由于我有多个具有不同返回类型的端点,因此似乎我必须有一堆相似的类型,但只有一个字段存在差异。当我执行 $lookup 操作时需要这样做,这基本上类似于关系数据库中的 join 操作。

我认为我的意思的问题可以从示例中清楚地看出:

type Post struct {
  title string
  author string
  category string
}

type Author struct {
  firstname string
  lastname string
}

type Category struct {
  name string
  parent Category
}

type PostWithAuthor struct {
  title string
  author Author
  category string
}

type PostWithCategory struct {
  title string
  author string
  category Author
}

type PostWithAuthorAndCategory struct {
  title string
  author Author
  category Category
}


func getPost() (Post) {
  
}

func getPostWithCategory() (PostWithCategory) {

}

func getPostWithAuthor() (PostWithAuthor) {

}

func getPostWithAuthorAndCategory() (PostWithAuthorAndCategory) {

}

正确答案


您可以在另一个结构体中使用一个结构体。

type Post struct {
  Title string
  Author Author
  Category Category
}

type Author struct {
  FirstName string
  LastName string
}

type Category struct {
  Name string
  Parent *Category
}

// Query via `gorm`
var posts []Post
db.Where(&Post{Category: Category{Name: "food"}}).Find(&posts)

以上就是《在 Golang 中,是否需要为每个用例创建独立的结构体?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>