去巡视时不要使用指针来结构变量中的文字 [英] go tour when to not use pointer to struct literal in a variable

查看:148
本文介绍了去巡视时不要使用指针来结构变量中的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照Go 旅程第28页第53页

它们显示一个变量,它是一个指向结构体的指针。为什么这不是默认行为?我对C不熟悉,所以很难将其包围。我唯一能看到什么时候使用指针可能没有什么好处的地方在于,结构字面量是唯一的,并且不会用于其他程序,因此您希望它尽可能快地被垃圾回收。我甚至不确定像Go这样的现代语言是否可以这样工作。



我的问题是这样的。什么时候应该将一个结构体指针指向一个变量,什么时候应该指定结构体本身?



谢谢。


<


  • 解决方案

使用指针而不仅仅是一个结构体时,这个结构很大,你可以通过它来传递你想共享的结构,也就是说所有的修改都会影响你的结构,而不会影响副本
>

在其他情况下,简单地使用结构体就可以了。对于一个小结构,你可以像使用 int * int 一样思考问题:大多数int int很好,但有时你传递一个指针,以便接收者可以修改你的int变量。



在你连接的Go游览练习中,Vertex结构很小并且具有与任何数目相同的语义。在我看来,直接使用它作为结构并在 Scaled 函数会很好53rel =noreferrer>#53 像这样:

  func(v Vertex)Scaled(f float64 )顶点{
vX = vX * f
vY = vY * f
返回v
}

,因为有

  v2:= v1.Scaled(5)

会创建一个新的顶点,就像

  var f2 float32 = f1 * 5 

创建一个新的 float



类似于如何处理标准 Time struct(定义的此处),通常保存在时间而不是 *时间



但没有明确的规则,根据使用情况,我可以很好地保存 Scale 缩放


Per the Go tour page 28 and page 53

They show a variable that is a pointer to a struct literal. Why is this not the default behavior? I'm unfamiliar with C, so it's hard to wrap my head around it. The only time I can see when it might not be more beneficial to use a pointer is when the struct literal is unique, and won't be in use for the rest program and so you would want it to be garbage collected as soon as possible. I'm not even sure if a modern language like Go even works that way.

My question is this. When should I assign a pointer to a struct literal to a variable, and when should I assign the struct literal itself?

Thanks.

解决方案

Using a pointer instead of just a struct literal is helpful when

  • the struct is big and you pass it around
  • you want to share it, that is that all modifications affect your struct instead of affecting a copy

In other cases, it's fine to simply use the struct literal. For a small struct, you can think about the question just as using an int or an *int : most of the times the int is fine but sometimes you pass a pointer so that the receiver can modify your int variable.

In the Go tour exercises you link to, the Vertex struct is small and has about the same semantic than any number. In my opinion it would have been fine to use it as struct directly and to define the Scaled function in #53 like this :

func (v Vertex) Scaled(f float64) Vertex {
    v.X = v.X * f
    v.Y = v.Y * f
    return v
}

because having

v2 := v1.Scaled(5)

would create a new vertex just like

var f2 float32 = f1 * 5

creates a new float.

This is similar to how is handled the standard Time struct (defined here), which is usually kept in variables of type Time and not *Time.

But there is no definite rule and, depending on the use, I could very well have kept both Scale and Scaled.

这篇关于去巡视时不要使用指针来结构变量中的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆