day8方法 定义方法

master
独孤伶俜 2022-12-12 02:00:55 +08:00
parent 4cb65ecbac
commit bb4af455d5
1 changed files with 72 additions and 0 deletions

View File

@ -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"
}