繁体   English   中英

如何从 Go 中的字符串列表中初始化类型、字符串切片

[英]How to initialise type, slice of strings, from a list of strings in Go

假设我有以下内容:

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

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

type CityNamesReponse []string

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

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

我不想循环数据,只想在一个 go 中完成。 也试过:

return &CityNameResponse{ ...dbResult.CityNames}

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

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

谢谢

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

请使用从[]stringCityNamesReponse转换

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM