登录
首页 >  Golang >  Go问答

Why should I use the & sign on structs?

来源:Golang技术栈

时间:2023-03-21 07:56:01 223浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Why should I use the & sign on structs?》,主要内容是讲解golang等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

In the gotour, there is a section: struct literals.

package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
   v1 = Vertex{1, 2}  // has type Vertex
   v2 = Vertex{X: 1}  // Y:0 is implicit
   v3 = Vertex{}      // X:0 and Y:0
   p  = &Vertex{1, 2} // has type *Vertex
)

func main() {
   fmt.Println(v1, p, v2, v3)
}

What's the difference between a struct with an ampersand and the one without? I know that the ones with ampersands point to the same reference, but why should I use them over the regular ones?

 var p = &Vertex{} // why should I use this
 var c = Vertex{} // over this

正确答案

The comments pretty much spell it out:

   v1 = Vertex{1, 2}  // has type Vertex
   p  = &Vertex{1, 2} // has type *Vertex

As in many other languages, & takes the address of the identifier following it. This is useful when you want a pointer rather than a value.

If you need to understand more about pointers in programming, you could start with this for go, or even the wikipedia page.

今天关于《Why should I use the & sign on structs?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表