猿问

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

假设我有以下内容:


一个结构

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

谢谢


慕田峪7331174
浏览 183回答 1
1回答

开心每一天1111

不要使用指向切片的指针。指针可能会损害性能并使代码复杂化。请使用从to的转换。[]stringCityNamesReponsefunc GetCities() CityNamesReponse{   dbResult := MyStructure{       Field1:   1,       CityNames: []string{"Amsterdam", "Barcelona"},   }   return CityNameResponse(dbResult.CityNames)}如果您觉得必须使用指向切片的指针,请使用从to的转换。*[]string*CityNameReponsefunc GetCities() *CityNamesReponse{   dbResult := MyStructure{       Field1:   1,       CityNames: []string{"Amsterdam", "Barcelona"},   }   return (*CityNameResponse)(&dbResult.CityNames)}
随时随地看视频慕课网APP

相关分类

Go
我要回答