I am learning Go after 9 years of development in C ++. In C ++, it is bad practice to pass arguments to functions by value, except for variables of built-in types due to a penalty for performance: all fields of the argument will be copied, and in most cases it will be a very expensive operation.
Is this true for Go? It seems very expensive to pass "this" by value only to assign the semantics of "const". Is the Go compiler smart enough to prevent a variable from changing before the first modification? Why doesnβt the "this" value by value go anti-pattern in Go, as it is in C / C ++?
, , , .
Go - , :
package main import "fmt" type Something struct { Value int } func (s *Something) ChangeValue(n int) { s.Value = n } func main() { o := new(Something) // o is of type *Something fmt.Println(o.Value) // Prints 0 o.ChangeValue(8) // Changes o.Value to 8 fmt.Println(o.Value) // Prints 8 (*Something).ChangeValue(o, 16) // Same as calling o.ChangeValue(16) fmt.Println(o.Value) // Prints 16 }
, , , ChangeValue Something ...
ChangeValue
Something
! o Value. .
o
Value
"this" Go . , "const". Go "const" . , , - - , .
BTW, "this" "self" "receiver" , . IIRC, "this" "self" , Go - ( ).
, , , - this self. , .
this
self
, , , :
func (n *node) walk(f func(*node)) { for n != nil { f(n) n = n.next } }
, ++ Go , , ( ), ( , int).
, , map channel s. , , , ( ), , , .
map
channel
string - , , .
string
this , Go - ( , ++), , , , .
. , , ( ), , . , , , .
Go , . ++ , .
, , , API.