type Point struct{ X, Y float64 }
// traditional function
func Distance(p, q Point) float64 {
return math.Hypot(q.X-p.X, q.Y-p.Y)
}
// same thing, but as a method of the Point type
func (p Point) Distance(q Point) float64 {
return math.Hypot(q.X-p.X, q.Y-p.Y)
}
p := Point{1, 2}
q := Point{4, 6}
fmt.Println(Distance(p, q)) // "5", function call
fmt.Println(p.Distance(q))
// "5", method call
func (p *Point) ScaleBy(factor float64) {
p.X *= factor
p.Y *= factor
}
// An IntList is a linked list of integers.
// A nil *IntList represents the empty list.
type IntList struct {
Value int
Tail
*IntList
}
// Sum returns the sum of the list elements.
func (list *IntList) Sum() int {
if list == nil {
return 0
}
return list.Value + list.Tail.Sum()
}
package main
import (
"fmt"
)
type Point struct{ X, Y float64 }
func (p *Point) ins() {
p.X++
p.Y++
}
type ColoredPoint struct {
Point
Color string
}
func main() {
cp := &ColoredPoint{
Point: Point{X: 5, Y:6},
Color: "red",
}
cp.ins()
fmt.Println(cp)
}
package main
import (
"fmt"
)
type Point struct{ X, Y float64 }
func (p *Point) ins() {
p.X++
p.Y++
}
type ColoredPoint struct {
*Point
Color string
}
func main() {
cp := &ColoredPoint{
&Point{X: 5, Y:6},
"red",
}
cp.ins()
fmt.Println(cp)
fmt.Println(cp.Point)
fmt.Println(cp.X)
fmt.Println(cp.Y)
fmt.Println(cp.Color)
}
p := Point{1, 2}
q := Point{4, 6}
distanceFromP := p.Distance // method value
fmt.Println(distanceFromP(q)) // "5"
var origin Point // {0, 0}
fmt.Println(distanceFromP(origin)) // "2.23606797749979", sqrt(5)
scaleP := p.ScaleBy // method value
scaleP(2) // p becomes (2, 4)
scaleP(3) // then (6, 12)
scaleP(10) // then (60, 120)
type Rocket struct { /* ... */ }
func (r *Rocket) Launch() { /* ... */ }
r := new(Rocket)
time.AfterFunc(10 * time.Second, func() { r.Launch() })
//上下等价
time.AfterFunc(10 * time.Second, r.Launch)
原文:https://www.cnblogs.com/laiyuanjing/p/11240216.html