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学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
-
193 收藏
-
354 收藏
-
418 收藏
-
161 收藏
-
209 收藏
-
Golang · Go问答 | 10小时前 | channel · sync.Cond · 架构设计 · 并发编程 · Go问答 · Go channel 条件变量 sync.Cond 并发等待 广播唤醒432 收藏
-
255 收藏
-
419 收藏
-
Golang · Go问答 | 1天前 | 并发 · Go问答 · Go测试 · testing/synctest · 虚拟时间 · time.Sleep Go 1.25 testing/synctest Go并发测试 虚拟时间 flaky test246 收藏
-
493 收藏
-
Golang · Go问答 | 1天前 | GC · sync.Pool · bytes.Buffer · 内存优化 · Go问答 · Go 垃圾回收 内存占用 对象池 sync.Pool bytes.Buffer buffer复用307 收藏
-
333 收藏
-
Golang · Go问答 | 1天前 | 配置 · 设计模式 · 架构 · Go问答 · 代码重构 · Go 默认值 配置参数 参数校验 构造函数 option Functional Options100 收藏
-
246 收藏
-
251 收藏
-
Golang · Go问答 | 2天前 | 依赖注入 · 设计模式 · api设计 · Go问答 · Functional Options · API设计 默认值 依赖注入 Go问答 Functional Options 函数选项153 收藏
-
Golang · Go问答 | 2天前 | 单元测试 · HTTP · Go问答 · httptest · ResponseRecorder · 单元测试 HTTP响应 httptest Go问答 ResponseRecorder Handler测试481 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习