GO结构体:不一样的面向对象
2019-06-18 本文已影响0人
mick_
package main
import (
"math"
"fmt"
)
// 声明一个结构体
type Point struct{
x float64
y float64
}
// TODO 输出接收者的值,引用类型的值是地址
// TODO 返回两点之间的距离的计算结果
func(p *Point) Distance(q Point)float64{
fmt.Printf("%p\n",p)
return math.Hypot(p.x-q.x,p.y-q.y)
}
// TODO 返回两点之间的距离的计算结果
func Distance(p,q Point) float64{
return math.Hypot(p.x-q.x,p.y-q.y)
}
// 方法与函数之间的区别
// 1 方法是带有隐士第一个传参的函数
// 2 接收者的命名规范用其类型的第一个字母小写,保持传递的一致性与简短性
// 3 关键字func与函数名之间部分叫做接收者包括 类型与类型的变量值
// 4 方法使用选择器调用p.Distance(p2)
// 第二个示例
type Path []Point
func(p Path) Distance(){
fmt.Printf("%p\n",p)
}
func(p *Path) Add(){
fmt.Printf("%p\n",p)
*p = append(*p,Point{100,100})
}
func main(){
per := Path{{1,1},{2,2}}
fmt.Printf("%p\n",&per)
fmt.Printf("%p\n",per)
per.Distance()
per.Add()
per.Distance()
fmt.Printf("%p\n",per)
fmt.Println(per)
//fmt.Println(per.Distance)
//p := Point{3,3}
//p2 := Point{1,1}
//d := p.Distance(p2)
//fmt.Printf("%p\n",&p)
//d2 := Distance(p,p2)
//fmt.Println(d,d2)
}