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

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。