Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Created July 31, 2019 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilovejs/9a4fbb5b490f020c82a380a237ecd3d7 to your computer and use it in GitHub Desktop.
Save ilovejs/9a4fbb5b490f020c82a380a237ecd3d7 to your computer and use it in GitHub Desktop.
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)
}
@ilovejs
Copy link
Author

ilovejs commented Jul 31, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment