如何在golang中区分引用和值类型

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

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.

huangapple
  • 本文由 发表于 2022年11月18日 10:08:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/74484192.html
匿名

发表评论

匿名网友

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

确定