2

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

2
  • Won't mere CityNameResponse(dbResult.CityNames) work for you? Commented Jun 2, 2020 at 16:13
  • Yes, it did. I knew it was something simple but I could not find the syntax Commented Jun 2, 2020 at 20:05

1 Answer 1

7

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. Very helpful was searching for something for this but did not find the syntactics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.