diff --git a/src/study/day8Method/MethodStatement.go b/src/study/day8Method/MethodStatement.go new file mode 100644 index 0000000..326d3d2 --- /dev/null +++ b/src/study/day8Method/MethodStatement.go @@ -0,0 +1,72 @@ +package main + +import ( + "fmt" + "math" +) + +// 在函数声明时, 在其函数名之前放上一个变量, 即是一个方法 +// 附加的变量被称为"接受者" + +// 这个函数会被附加到这个"接受者"所在的类型上 +// 可以说就是为这个"接受者"所在的类型创建了一个独占的函数 + +//⚠️注意内置的这些 int float32 这些内置的类型不能被传入"接受者" +// 我试了试,关键字应该都是不能被type创建类型的 + +type myInt int + +var i myInt + +// MethodStart 此时 MethodStart 函数就被绑定给了所有的myInt类型的值使用, 这就是myInt类型的一个方法 +func (i myInt) MethodStart() { + fmt.Printf("(%T, %[1]v)\n", i) +} + +// Point 下面是个例子 +type Point struct{ X, Y float64 } + +// Distance traditional function +func Distance(p, q Point) float64 { + return math.Hypot(q.X-p.X, q.Y-p.Y) +} + +// Path 不同的类型可以有同名的方法, 不同类型的调用,将会指向不同的方法, 实现不同的功能 +// A Path is a journey connecting the points with straight lines. +type Path []Point + +// Distance returns the distance traveled along the path. +func (path Path) Distance() float64 { + sum := 0.0 + for i := range path { + if i > 0 { + sum += path[i-1].Distance(path[i]) + } + } + return sum +} + +// Distance 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) +} +func main() { + var i myInt = 1 + i.MethodStart() + a := Point{X: 233, Y: 233} + b := Point{X: 3, Y: 3} + + // 传统函数也能够轻松实现此功能 + fmt.Println(Distance(a, b)) + // 但是使用 方法就无疑轻松很多了 + fmt.Println(a.Distance(b)) + + perim := Path{ + {1, 1}, + {5, 1}, + {5, 4}, + {1, 1}, + } + fmt.Println(perim.Distance()) // "12" + +}