假设我有以下内容:一个结构type MyStructure struct { Field1 int CityNames []string}-a 类型,我用作响应。我创建这种类型只是为了在阅读时使响应比一段字符串更具暗示性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谢谢
1 回答

开心每一天1111
TA贡献1836条经验 获得超13个赞
不要使用指向切片的指针。指针可能会损害性能并使代码复杂化。
请使用从to的转换。[]stringCityNamesReponse
func GetCities() CityNamesReponse{
dbResult := MyStructure{
Field1: 1,
CityNames: []string{"Amsterdam", "Barcelona"},
}
return CityNameResponse(dbResult.CityNames)
}
如果您觉得必须使用指向切片的指针,请使用从to的转换。*[]string*CityNameReponse
func GetCities() *CityNamesReponse{
dbResult := MyStructure{
Field1: 1,
CityNames: []string{"Amsterdam", "Barcelona"},
}
return (*CityNameResponse)(&dbResult.CityNames)
}
- 1 回答
- 0 关注
- 182 浏览
添加回答
举报
0/150
提交
取消