Reputation:
I'm learning go and came across this piece of code on go tour:
package main
import (
"fmt"
"math"
)
type MyFloat int
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
func (f MyFloat) run() string{
fmt.Println("This is called")
return "Hey there"
}
func main() {
f := MyFloat(-math.Sqrt2)
fmt.Println(f.Abs())
fmt.Println(f.run())
}
Here we declare a type named MyFloat and return type is float64. I was thinking that I can declare methods which only returns float64. I declared a method named run()
in the above case which returns string. How is this possible? Why can't I just declare the type with no specific return type like this type MyFloat
?
Upvotes: 1
Views: 562
Reputation: 31691
You are confusing types and methods. As putu already menitioned in a comment, types don't "return" anything. In a kind of handwavy way most types are just data structures that you can attach methods to*.
Another way to write the methods in your example is this:
// func (f MyFloat) Abs() float64 {
func Abs(f MyFloat) float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
// func (f MyFloat) run() string {
func run(f MyFloat) string {
fmt.Println("This is called")
return "Hey there"
}
Note that the function bodies are no different at all. The difference is just in how you call these functions. Semantically they are equivalent. The receiver of a method becomes the implicit first argument to a function.
[*] This ignores function types, which don't hold data. net/http.HandlerFunc is a prominent example in the standard library.
type HandlerFunc func(ResponseWriter, *Request)
Upvotes: 1