编程语言13、GO语言没有类-GOLANG
xiugo语言不支持类和对象,也不支持继承,但是通过go提供的结构和方法可以实现面向对象设计的概念
绑定方法到结构
DMS格式,度,分,秒表示坐标,每60秒为一分,每60分为一度,编写一个decimal()方法实现将坐标转换为十进制单位为度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package main
import "fmt"
type coordinate struct { d, m, s float64 h rune }
func (c coordinate) decimal() float64 { sign := 1.0 switch c.h { case 'S', 'W', 's', 'w': sign = -1 } return sign * (c.d + c.m/60 + c.s/3600) } func main() { lat := coordinate{4, 35, 22.2, 'S'} long := coordinate{137, 26, 30.12, 'E'}
fmt.Println("纬度:", lat.decimal(), "经度:", long.decimal()) }
|
构造函数
初始化结构的同时将经纬度转换为更友好的十进制单位
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package main
import "fmt"
type coordinate struct { d, m, s float64 h rune } type location struct { lat, long float64 }
func (c coordinate) decimal() float64 { sign := 1.0 switch c.h { case 'S', 'W', 's', 'w': sign = -1 } return sign * (c.d + c.m/60 + c.s/3600) } func main() { lat1 := coordinate{4, 35, 22.2, 'S'} long1 := coordinate{137, 26, 30.12, 'E'}
curiosity := location{lat1.decimal(), long1.decimal()} fmt.Println(curiosity)
}
|
go语言没有提供专用的构造方法,但是在约定俗成的函数名称以New,new关键字开头的函数一般是初始化某个类型的构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package main
import "fmt"
type coordinate struct { d, m, s float64 h rune } type location struct { lat, long float64 }
func (c coordinate) decimal() float64 { sign := 1.0 switch c.h { case 'S', 'W', 's', 'w': sign = -1 } return sign * (c.d + c.m/60 + c.s/3600) } func newLocation(lat, long coordinate) location { return location{lat.decimal(), long.decimal()} }
func main() { curiosity := newLocation(coordinate{4, 35, 22.2, 'S'}, coordinate{137, 26, 30.12, 'E'}) fmt.Println(curiosity)
}
|
类的替代品
go语言通过结构和方法来满足传统编程语言的类的需求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package main
import ( "fmt" "math" )
type location struct { lat, long float64 }
type world struct { radius float64 }
func (w world) distance(p1, p2 location) float64 { s1, c1 := math.Sincos(rad(p1.lat)) s2, c2 := math.Sincos(rad(p2.lat)) clong := math.Cos(rad(p1.long - p2.long)) return w.radius * math.Acos(s1*s2+c1*c2*clong) }
func rad(deg float64) float64 { return deg * math.Pi / 180 }
func main() { var mars = world{radius: 3389.5} spirit := location{-14.5684, 175.472636} opportunity := location{-1.9462, 354.4734} dist := mars.distance(spirit, opportunity) fmt.Printf("%f km\n", dist) }
|