【发布时间】: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)不适合你吗? -
是的,确实如此。我知道这很简单,但我找不到语法