结构体struct 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 35 36 37 38 39 40 41 42 43 44 package mainimport "fmt" type myint int type Book struct { title string auth string } func changeBook (book Book) { book.auth = "666" } func changeBook2 (book *Book) { book.auth = "777" } func main () { var book1 Book book1.title = "Golang" book1.auth = "zhang3" fmt.Printf("%v\n" , book1) changeBook(book1) fmt.Printf("%v\n" , book1) changeBook2(&book1) fmt.Printf("%v\n" , book1) }
类 GO语言中的类,主要实现就是通过结构体区绑定方法。
这里主要主要的首字母大小写:
如果类名首字母大写,表示其他包也能够访问 类似于Public 公有的方法
如果说类的属性首字母大写, 表示该属性是对外能够访问的,否则的话只能够类的内部访问
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 35 36 37 38 package mainimport "fmt" type Hero struct { Name string Ad int level int } func (this *Hero) Show() { fmt.Println("Name = " , this.Name) fmt.Println("Ad = " , this.Ad) fmt.Println("Level = " , this.level) } func (this *Hero) GetName() string { return this.Name } func (this *Hero) SetName(newName string ) { this.Name = newName } func main () { hero := Hero{Name: "zhang3" , Ad: 100 } hero.Show() hero.SetName("li4" ) hero.Show() }
类的继承 1 2 3 4 5 6 type Father struct { Hero Ad int level int } //类的继承直接加入结构体里面就好了
接口 父类申请一个接口,子类不需要继承,直接实现全部方法就好了
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 package mainimport "fmt" type AnimalIF interface { Sleep() GetColor() string GetType() string } type Cat struct { color string } func (this *Cat) Sleep() { fmt.Println("Cat is Sleep" ) } func (this *Cat) GetColor() string { return this.color } func (this *Cat) GetType() string { return "Cat" } type Dog struct { color string } func (this *Dog) Sleep() { fmt.Println("Dog is Sleep" ) } func (this *Dog) GetColor() string { return this.color } func (this *Dog) GetType() string { return "Dog" } func showAnimal (animal AnimalIF) { animal.Sleep() fmt.Println("color = " , animal.GetColor()) fmt.Println("kind = " , animal.GetType()) } func main () { var animal AnimalIF animal = &Cat{"Green" } animal.Sleep() animal = &Dog{"Yellow" } animal.Sleep() cat := Cat{"Green" } dog := Dog{"Yellow" } showAnimal(&cat) showAnimal(&dog) }
interface{} 提供 “类型断言” 的机制 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 mainimport "fmt" func myFunc (arg interface {}) { fmt.Println("myFunc is called..." ) fmt.Println(arg) value, ok := arg.(string ) if !ok { fmt.Println("arg is not string type" ) } else { fmt.Println("arg is string type, value = " , value) fmt.Printf("value type is %T\n" , value) } } type Book struct { auth string } func main () { book := Book{"Golang" } myFunc(book) myFunc(100 ) myFunc("abc" ) myFunc(3.14 ) }