Method receivers
Go method receivers take a type along with a variable name for the type, for example:
type MyFloat float64
func (x MyFloat) Abs() float64 {
if x < 0 {
return float64(-x)
}
return float64(x)
}
func main() {
f := MyFloat(-math.Sqrt2)
fmt.Println(f.Abs())
}
The receiver takes "x"
along with the type of the receiving method. What is the meaning of the name "x". Since I can call a method on any MyFloat instance (not just an instance named x), why should I specify x? Since the receiver is a type or a reference to a type, why not just take a type or pointer one like this
func (MyFloat) Abs() float64 {
if this < 0 {
return float64(-this)
}
return float64(this)
}
My guess is instead this
in Java Golang allows any name? This is true?
source to share
Your guess is accurate: the receiver must be explicitly specified in the method definition. This avoids any ambiguity. In your example, how could the Go compiler know that x is the receiver?
Note that using "self" or "this" or "me" as the recipient name is considered unsuccessful in go. The name should be short - one letter is fine. See more information at https://code.google.com/p/go-wiki/wiki/CodeReviewComments#Receiver_Names
source to share
I think you are not using it correctly, you should be using it in a struct.Where the receiver makes a reference to the fields of the structure.
For example:
package main
import "fmt"
type Decimal struct {
first float64
}
func (x Decimal) out() float64 {
return x.first
}
func main() {
var start Decimal
start.first = 10.8
show := start.out()
fmt.Println(show)
}
source to share
It's a design choice.
Using Java this
, Go-lang choose another mechanic.
In Go, it is legal to make the receiver a pointer or not.
We'll see:
func (t Type) Id() { return t }
func (t *Type) IdPointer() { return t }
What if Go uses Java design?
It will be:
func (Type) Id() { return this }
func (*Type) IdPointer() { return this }
First, it's confusing what it (*Type)
is.
Second, it can also be a pointer or a value. Also confused.
But, anyway, you can design Go-lang like this.
It's a choice in the end.
source to share