類型系統
繼承數組
package main import ( "fmt" ) type Integer int func (a Integer) Less(b Integer) bool { return a > b } func main() { var integer Integer = 1 fmt.Println(integer.Less(0)) } // print -> true
指針運算符 *指針
package main import ( "fmt" ) type Person struct { Id string Name string } func main() { p1 := Person{"1", "張三"} p2 := &p1 p1.Id = "2" fmt.Println(p1, *p2) } // print -> {2 張三} {2 張三}
取址符 &code
package main import ( "fmt" ) type Person struct { Id string Name string } func main() { p1 := Person{"1", "張三"} p2 := &p1 p1.Id = "2" fmt.Println(p1, p2) } // print -> {2 張三} &{2 張三}
&取址可讓p1與p2共享同一塊數據內存,從而在修改的時候p1與p2的結果相同。對象
非取址繼承
package main import ( "fmt" ) type Person struct { Id string Name string } func main() { p1 := Person{"1", "張三"} p2 := p1 p1.Id = "2" fmt.Println(p1, p2) } // print -> {2 張三} {1 張三}
Go 語言的基本類型在賦值的時候,其實是值傳遞,包括複合類型,這點與其餘的面嚮對象語言方式不一樣,須要在開發的時候額外注意。接口
數組切片、map、channel、interface
數組切片內存
package main import ( "fmt" ) func main() { a1 := []int{1, 2, 3} a2 := a1 a1[0] = 10 fmt.Println(a1, a2) } // print -> [10 2 3] [10 2 3]
map 開發
package main import ( "fmt" ) func main() { m1 := map[string]string{"1": "hi"} m2 := m1 m1["1"] = "ok" fmt.Println(m1, m2) } // print -> map[1:ok] map[1:ok]
channelstring
intefaceimport
interface 接口
package main import ( "fmt" ) type Person struct { Name string } func (p *Person) Find() { fmt.Println("find person") } type IFind interface { Find() } type IString interface { String() } func main() { var f IFind = new(Person) f.Find() } // print -> find person
interface
package main import ( "fmt" ) type Integer int func (a Integer) Less(b Integer) bool { return a < b } func (a Integer) Add(b Integer) { a += b } type LessAdder interface { Less(b Integer) bool Add(b Integer) } func main() { var a Integer = 1 var b LessAdder = a fmt.Println(a, b) } // print -> 1 1