Is there a penalty for passing "this" by value in Go methods?

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 ++?

+5
source share
4 answers

, , , .

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 ...

! o Value. .

+8

"this" Go . , "const". Go "const" . , , - - , .

BTW, "this" "self" "receiver" , . IIRC, "this" "self" , Go - ( ).

, , , - this self. , .

, , , :

func (n *node) walk(f func(*node)) {
        for n != nil {
                f(n)
                n = n.next
        }
}
+6

, ++ Go , , ( ), ( , int).

, , map channel s. , , , ( ), , , .

string - , , .

this , Go - ( , ++), , , , .

+5

. , , ( ), , . , , , .

Go , . ++ , .

, , , API.

+5

All Articles