Created
July 31, 2019 04:22
-
-
Save ilovejs/9a4fbb5b490f020c82a380a237ecd3d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func main() { | |
var i interface{} | |
describe(i) | |
i = 42 | |
describe(i) | |
i = "hello" | |
describe(i) | |
// | |
v := &Vertex{3, 4} | |
fmt.Println(v.Abs()) | |
} | |
type MyFloat float64 | |
func (f MyFloat) Abs() float64 { | |
if f < 0 { | |
// neg | |
return float64(-f) | |
} | |
return float64(f) | |
} | |
type Vertex struct { | |
X, Y float64 | |
} | |
// method | |
func (v Vertex) Abs() float64 { | |
return math.Sqrt(v.X*v.X + v.Y*v.Y) | |
} | |
// methods are function | |
func Abs(v Vertex) float64 { | |
return math.Sqrt(v.X*v.X + v.Y*v.Y) | |
} | |
// pointer receiver | |
// This means the receiver type has the literal syntax *T for some type T. | |
// Also, T cannot itself be a pointer such as *int | |
func (v *Vertex) Scale(f float64) { | |
v.X = v.X * f | |
v.Y = v.Y * f | |
} | |
func describe(i interface{}) { | |
fmt.Printf("(%v, %T)\n", i, i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://tour.golang.org/methods/4