Yes and yes.
> Next question is why is this done? I understand passing arguments by value,
> but why the objects themselves? Under the hood, is Go only about structs and
> functions?
If you want to pass by reference instead, you can re-write the method as
func (self *T) inc() {
self.x++
}
- Evan
Go is just providing options. You can declare methods so that they
operate on a pointer (pass by reference) or so that they make a copy
(pass by value). You can do that with any other parameter, so why not
the receiver too?
A method receiver is still a special parameter in Go, but not quite as
special as it is in some other languages.
- Evan
> Thanks Evan, You've confirmed the mechanics of what I thought is going on. I'm still stuck on the "why". In C++ or Python calling an object's method doesn't copy the object. This seems pretty inefficient to me, so there must be a reason.
It doesn't copy "the object". It copies the receiver of the method, because, like in all programming languages you are likely to know, Go is call-by-value and it copies the arguments to the stack in order to pass them to the function. The receiver is just the first argument to the underlying function that implements the method.
If you call, in C, printf("%d", i), IT COPIES i TO THE STACK. That's what we mean by copy.
This is not rocket science. It's barely even computer science.
A method is a function with an implicit first argument, called a receiver.
So when you call a method:
- if the receiver is a pointer to int, it copies the pointer to int.
- if the receiver is a struct, it copies the struct.
- if the receiver is a pointer to struct, it copies the pointer to struct.
Do you see the pattern?
By the way, or maybe central to your view, that last case is exactly what Java always does. Go is not so rigid, but if you declare your type T to have methods with receiver type *T, you get the behavior you're after.
-rob