当我将变量传递给golang中的私有方法时,它会创建一个新实例吗?
If I have main function:
var a = "foo"
modify(a)
fmt.Println(a)
where
func modify(s string) error {
s = "bar"
}
will the result be "foo"
or "bar"
?
如果我有主要功能: p>
var a =“ foo“
modify(a)
fmt.Println(a)
code> pre>
其中 p>
func Modify(s 字符串)错误{
s =“ bar”
}
code> pre>
结果将是“ foo” code>或“ bar “ code>? p>
div>
None. It won't compile because neither 'foo'
nor 'bar'
is a single character. But let's say you used double quotes instead.
In Golang, arguments are passed by value (they are copied to the new place in memory - stack or heap), and it does not matter whether it is a private or a public method or arbitrary function. The new instance is modified. The result of your example will be "foo"
.
In order to modify variable lying outside of the function, you have to explicitly pass the pointer pointing to such variable.
func modify(s *string) {
*s = "bar"
}
...
var a = "foo"
modify(&a)
println(a) // will print "bar"
In this case pointer itself is passed by values (it is copied) but its value (the address of a
) still points to the same variable. So the a
can by modified through the pointer.