【问题标题】:How to initialise type, slice of strings, from a list of strings in Go如何从 Go 中的字符串列表初始化类型、字符串切片
【发布时间】:2020-09-21 04:14:20
【问题描述】:

假设我有以下内容:

  • 一个结构
type MyStructure struct {
    Field1     int
    CityNames   []string
}

-一种类型,我用作响应。我创建这种类型只是为了在阅读时使响应比一段字符串更具暗示性

type CityNamesReponse []string

然后我有一个函数,我想从我的结构中获取名称并将其放入响应中

func GetCities() *CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return &CityNameResponse{ dbResult.CityNames}
}

我不想循环数据,只想一次性完成。也试过了:

return &CityNameResponse{ ...dbResult.CityNames}

可以这样做,但我是 Go 新手,有点困惑,想以正确的方式做。这感觉不太好:

    // This works
    c := dbResults.CityNames
    response := make(CityNameResponse, 0)
    response = c
    return &response

谢谢

【问题讨论】:

  • CityNameResponse(dbResult.CityNames) 不适合你吗?
  • 是的,确实如此。我知道这很简单,但我找不到语法

标签: go types


【解决方案1】:

不要使用指向切片的指针。指针可能会损害性能并且使代码复杂化。

请使用从[]stringCityNamesReponseconversion

func GetCities() CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return CityNameResponse(dbResult.CityNames)
}

如果您觉得必须使用指向切片的指针,请使用从*[]string*CityNameReponseconversion

func GetCities() *CityNamesReponse{
   dbResult := MyStructure{
       Field1:   1,
       CityNames: []string{"Amsterdam", "Barcelona"},
   }
   return (*CityNameResponse)(&dbResult.CityNames)
}

【讨论】:

  • 谢谢。非常有帮助的是为此搜索一些东西,但没有找到语法。
猜你喜欢
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2013-05-20
  • 2023-03-21
  • 2018-12-24
  • 1970-01-01
  • 2011-03-09
相关资源
最近更新 更多