亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
慕田峪7331174 2022-06-06 17:10:37
假設我有以下內容:一個結構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)

}


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號