登录
首页 >  Golang >  Go问答

将复杂系统简化

来源:stackoverflow

时间:2024-02-27 11:00:17 435浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《将复杂系统简化》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

假设我调用了一个 api,它返回一个结构体切片,每个结构体都包含大量方法和字段,但我只想为返回值的每个元素使用一个字段。我怎样才能做到这一点?

例如,我调用一个 api,它返回 x 元素的切片,每个元素都有 4 个值和 13 个方法,但我只想要 1 个值和 0 个方法(胎儿结构的切片)。我如何将其编组到我自己的结构中?例如:

func GETApi() []fetus {
//doGet() returns a slice of persons, which are described below 
a := doGet()  // this gets many detailed persons as a slice, but I just want them as a slice of fetus
/*
 type person struct {
  id: 
  age:
  height: 
  width:
 }

func (a *person) GetHeight() int { ... }
func (a *person) GetWidth() int { ... }
func (a *person) GetLaught() int { ... }

// I want to return a slice of these ([]fetus)
type fetus struct {
  id: 
 }
var f fetus 
f := a  // how can I condense said slice of persons into a slice of fetus
return f
*/

正确答案


也许是这样的?

package main

type Person struct {
    Id string
    Name string
    Age string
    LotsOfOtherFields string
}

type Fetus struct {
    Id string
}

func main() {
    persons := []Person{
        {Id: "a", Name: "John"},
        {Id: "b", Name: "Steve"},
        {Id: "c", Name: "Fred"},
    }

    fetuses := make([]Fetus, len(persons))
    for i, p := range persons {
        // Create a new fetus struct and pluck the ID from the person struct
        fetuses[i] = Fetus{Id: p.Id}
    }
}

终于介绍完啦!小伙伴们,这篇关于《将复杂系统简化》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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