今天,看看GO的高级语言特性-方法和接口
废话不多说,直接上代码
*************************************************
1 package main
2
3 import (
4 "fmt"
5 "math"
6 )
7
8 type Vertex struct {
9 X, Y float64
10 }
11
12 func (v *Vertex) Abs() float64 {
13 return math.Sqrt(v.X*v.X + v.Y*v.Y)
14 }
15
16 func (v Vertex) Scale(f float64) {
17 v.X = v.X * f
18 v.Y = v.Y * f
19 fmt.Println("v.X:", v.X, "v.Y:", v.Y)
20 }
21
22 type MyFloat float64
23
24 func (f MyFloat) Abs() float64 {
25 if f < 0 {
26 return float64(-f)
27 }
28 return float64(f)
29 }
30
31 type Abser interface {
32 Abs() float64
33 }
34
35 type MyImple struct {
36 data []int
37 }
38
39 func (f *MyImple) Read(b *[]int) (n int, err int) {
40 len := len(f.data)
41 tmp := make([]int, len)
42 *b = tmp
43 copy(*b, f.data)
44 return len, 0
45 }
46
47 func (f *MyImple) Write(b []int) (n int, err int) {
48 len := len(b)
49 tmp := make([]int, len)
50 copy(tmp, b)
51 f.data = tmp
52 return len, 0
53 }
54
55 func main() {
56 v := &Vertex{3, 4}
57 fmt.Println(v.Abs())
58 v.Scale(5)
59 fmt.Println(v)
60 f := MyFloat(-math.Sqrt2)
61 fmt.Println(f.Abs())
62 var a Abser
63 f1 := MyFloat(-math.Sqrt2)
64 v1 := Vertex{3, 4}
65 a = f1
66 fmt.Println(a.Abs())
67 a = &v1
68 fmt.Println(a.Abs())
69
70 type Read interface {
71 Read(b *[]int) (n int, err int)
72 }
73 type Write interface {
74 Write(b []int) (n int, err int)
75 }
76 type ReadWrite interface {
77 Read
78 Write
79 }
80 var t_data []int = []int{
81 1, 2, 3, 4, 5, 6,
82 }
83 var rw ReadWrite
84 var imple MyImple
85 rw = &imple
86 rw.Write(t_data)
87 var t_data_re []int
88 rw.Read(&t_data_re)
89 fmt.Println(t_data_re)
90 }
********************************
./test-go-advance
运行结果
5
v.X: 15 v.Y: 20
&{3 4}
1.4142135623730951
1.4142135623730951
5
[1 2 3 4 5 6]