如何定义一个函数,该函数接收一个指针作为参数并返回一个指向该参数的子代之一的指针?
问题描述:
I'm having my first contact with pointers now that I'm learning Go.
But this is getting a little tricky and I'm starting to question whether I'm doing it right or wrong.
The title is my best guess to try and explain what I'm trying to do in a foreign language, so if it's unclear, I can try to explain in a different way.
This is a simplified example of the code: https://play.golang.org/p/eultYp7Cq12
func hasCity(element string, state *State) (bool, *City) {
for _, city := range (*state).Cities {
if (city.Name == element) {
return true, &city
}
}
return false, nil
}
As you can see, the output is:
true &{Campinas}
[{SP [{São Paulo} {Barueri}]}]
But what I'm actually trying to get is:
true &{Campinas}
[{SP [{São Paulo} {Campinas}]}]
So, what am i doing wrong here?
答
The function returns the address of the local variable cities
. Change the code to return the address of the slice element:
func hasCity(element string, state *State) (bool, *City) {
for i, city := range state.Cities {
if city.Name == element {
return true, &state.Cities[i]
}
}
return false, nil
}