指针和调试在Go语言中的使用

huangapple go评论89阅读模式
英文:

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

Working example

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)

huangapple
  • 本文由 发表于 2014年7月15日 23:37:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/24762418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定