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

Viewed 68

Let's say I have the following:

  • a structure
type MyStructure struct {
    Field1     int
    CityNames   []string
}

-a type, that I used as a response. I created this type just to make the response more suggestive when reading than a slice of strings

type CityNamesReponse []string

then I have a function where I want to get from my structure just the Names and put it in the response

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

I do not want to loop over the data, just want to do it in one go. Tried also:

return &CityNameResponse{ ...dbResult.CityNames}

Could do it like this, but I am new in Go and a bit confused and would like to do it the right way. This doesn't feel good :

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

Thanks

1 Answers

Don't use a pointer to a slice. The pointer probably hurts performance and it complicates the code.

Do use a conversion from []string to CityNamesReponse.

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

If you feel that you must use a pointer to a slice, then use a conversion from *[]string to *CityNameReponse.

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