英文:
How to distinguish between reference and value in golang
问题
package main
type A struct {
Num int
}
func getA() A {
return A{Num: 10}
}
func main() {
if getA().Num == 10 {
// getA().Num = 20 // 为什么这行代码不起作用
myA := getA()
myA.Num = 20
}
}
为什么 "getA().Num = 20" 这行代码不起作用?
我不知道以下两种方式的区别:
myA := getA()
myA.Num = 20
和
//getA().Num = 20 // 为什么这行代码不起作用
我认为它们只是两行和一行的区别...
我更熟悉Java。
我需要了解什么才能理解它?
我期望代码能正确运行....
英文:
package main
type A struct {
Num int
}
func getA() A {
return A{Num: 10}
}
func main() {
if getA().Num == 10 {
// getA().Num = 20 // why not working
myA := getA()
myA.Num = 20
}
}
why "getA().Num = 20" line do not working?
I'm don't know the difference between
myA := getA()
myA.Num = 20
and
//getA().Num = 20 // why not working
I think it just two line and one line...
I'm more familiar with Java.
What I need to know to understand it?
I expected the code working correctly....
答案1
得分: 2
将你的函数声明调整如下,它将按照你的期望工作:
func getA() *A {
return &A{Num: 10}
}
改变的是getA
函数返回了一个指向类型A
的指针。
在Java中,类数据类型始终被用作引用(类似于指针),只是语言没有使用这样的显式表示法。因此,在编写Go代码时使用指针类型*A
与你在Java中所习惯的类似。
可能会让你困惑的是,Java没有直接等价于Go中的非指针类型,比如你Go代码中的普通A
类型。在Java中,你只能声明一个class
类型,它始终作为引用。
英文:
Tweak your function declaration like this, and it will work as you're expecting:
func getA() *A {
return &A{Num: 10}
}
What has changed is that getA
returns a pointer to a value of type A
.
In Java, class data types are always used as references (like a pointer), except the language doesn't use an explicit notation like this. So, writing Go code to use pointer types like *A
is similar to what you're used to in Java.
The part that may confuse you is that Java doesn't have a direct equivalent for Go's non-pointer types, like the plain A
in your Go code. In Java, you can only declare a class
type, which always acts as a reference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论