dtd5644 2018-09-18 15:52
浏览 44
已采纳

如何定义一个函数,该函数接收一个指针作为参数并返回一个指向该参数的子代之一的指针?

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?

  • 写回答

1条回答 默认 最新

  • dongyi1015 2018-09-18 15:57
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?