Is there a performance penalty for passing “this” by value in Go methods?

前端 未结 4 1821
天涯浪人
天涯浪人 2020-12-06 20:08

I\'m exploring Go after 9 years of C++ development. In C++ it is a bad practice to pass function\'s arguments by value except variables of built-in types because of performa

4条回答
  •  醉话见心
    2020-12-06 20:47

    "this" in Go is called a receiver. Yes, it may be very expensive to use a non pointer receiver only to emulate a "const" semantics. But Go dropped the "const" modifier for good reasons. Thus, it's probably not a good idea to take over that specific language design decision at the cost of unnecessary copying - in the case of anything bigger than few machine words.

    BTW, the terminology difference between "this" or "self" and "receiver" implies it has also different semantics. IIRC, one cannot change the value of "this" or "self" in some other languages, but in Go, the receiver is just another function parameter (actually the first one from the compiler's point of view).

    That said, this is the reason I discourage writing methods in which the receiver variable is named this or self. It's misleading for people used to some other languages.

    A completely made-up example illustrating hopefully the idea:

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

提交回复
热议问题