英文:
What's the difference between variable assignment and passing by reference?
问题
我对golang和编译语言一般都不太熟悉,所以请原谅我的无知。在像这样的代码中:
package main
import "fmt"
func assign() int {
return 1
}
func reference(foo *int) int {
*foo = 2
return 0
}
func main() {
var a, b int
a = assign()
reference(&b)
fmt.Println(a)
fmt.Println(b)
}
在将值分配给变量a和通过引用传递b之间,有什么实际的区别?
在实际的代码中,为什么json.Unmarshal()要求你传递一个指向空变量的指针,而不是直接返回解组后的值,以便你可以将其分配给你的变量?
英文:
I'm pretty new to golang, and compiled languages in general, so please excuse my ignorance. In some code like this:
package main
import "fmt"
func assign() int {
return 1
}
func reference(foo *int) int {
*foo = 2
return 0
}
func main() {
var a, b int
a = assign()
reference(&b)
fmt.Println(a)
fmt.Println(b)
}
...what is the practical difference between assigning the value to a vs. passing b by reference?
In terms of real-world code, why does json.Unmarshal() require you to pass a pointer to your empty variable rather than just returning the Unmarshalled value so you can assign it to your variable?
答案1
得分: 1
传值需要复制参数,但是在引用的情况下,你只需要发送对象的指针。Golang默认按值传递,包括切片。
关于json.Unmarshal的具体问题,我认为原因是为了使Unmarshal代码能够验证传入的对象是否包含与json中找到的兼容类型的相同字段名。例如,如果json中有一个重复的字段,在我们解组的对象中需要有一个相应的切片。
因此,我们需要传入我们想要将json字符串解组成的结构体。它需要是一个指针,这样Unmarshal才能填充字段。如果你只传递一个通用接口,Unmarshal将返回一个映射。如果Unmarshal没有接受指向结构体/接口的指针,它可能被实现为始终返回一个映射,但我认为这种方式更有用。
这是一个简单的例子,可能会有用- https://play.golang.org/p/-n8euepSS0
英文:
Passing by value requires copying of parameters, however in case of reference, you just send the pointer to the object. Golang does pass by value by default, including for slices.
For the specific question about json.Unmarshal, I believe the reason is so that the Unmarshal code can verify whether the object passed in contains the same field names with compatible types as found in the json. For example, if json has a repeated field, there needs to be a corresponding slice in the object we are unmarshaling into.
So, we need to pass in the struct that we want the json string to unmarshal into. It needs to be a pointer so that Unmarshal can populate the fields. If you just pass a generic interface, Unmarshal will return a map. If Unmarshal did not take a pointer to a struct/interface, it could have been implemented to always return a map, but I think it is more useful this way.
This is a simple example, but might be useful - https://play.golang.org/p/-n8euepSS0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论