Go method receivers take a type along with a variable name for the type, 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 receiving the method. What is the significance of the name 'x'. Since i am able to invoke the method on any instance of MyFloat ( not just on the one named as x ) why do i have to specify the x ? Since the receiver is a Type or a reference to a type why not simply take the type or the pointer alone like this
func (MyFloat) Abs() float64 {
if this < 0 {
return float64(-this)
}
return float64(this)
}
My assumption is instead of this
in Java golang allows any name? Is that so ?