英文:
Pointers and debugging in golang
问题
我被卡在一个情况中,无法弄清楚我搞砸了什么。最简单的解释可能是一个最小的例子:http://play.golang.org/p/14lbOBsCCo
我试图通过指针修改结构体的值,但最终修改了我想要的部分之外的一些内存。问题出在第92行。
你会如何调试这种情况(使用什么工具等),我如何设置broker.Port?
谢谢你的提示/建议!
英文:
I'm stuck in a situation and cannot figure out what I messed up. Easiest way to explain is probably some minimal example: http://play.golang.org/p/14lbOBsCCo
I am tying to modify a value of a struct via its pointer but end up modifing some memory other the part I want. Line 92 is where my issue is.
How would you debug a situation like this (tools etc.), and how do I get the broker.Port set?
Thanks for hints/suggestions!
答案1
得分: 6
你在整个过程中没有使用指针。首先,使用以下类型的注册表:
type Registry []*Broker
然后从这里开始进行工作。
至于调试技巧,这是我的过程:
- 值没有被改变,所以某个值被复制了
- 注意到注册表的类型是
[]Broker
,但我们想要修改经纪人,所以它需要是一个指针 - 将
type Registry
改为[]*Broker
- 继续尝试编译,让编译器告诉我每个需要指针而我们使用了值的地方(哇,编译时间快,静态类型)
英文:
You're not using pointers throughout. Start off with a Registry of type:
type Registry []*Broker
and work from there
As far as debugging tricks, this was my process:
- Value isn't being changed, so something is being copied by value
- Notice that Registry is type
[]Broker
, but we want to modify Brokers, so it needs to be a pointer - Change
type Registry
to[]*Broker
- Keep attempting to compile, letting the compiler tell me every place we are using a value where we need a pointer (woohoo fast compile times and static typing)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论