面向对象
go
package main
import "fmt"
// 声明类型
type myint int
func main() {
var a myint = 10
fmt.Println("a = ", a)
// type of a = main.myint
fmt.Printf("type of a = %T\n", a)
}结构体
go
//定义一个结构体
type Book struct {
title string
auth string
}
var book1 Book
book1.title = "Golang"
book1.auth = "zhang3"
fmt.Printf("%v\n", book1)
// 传递book的副本
changeBook(book1)
//指针传递
changeBook2(&book1)- 定义结构体方法
go
// 大写开头能被外部包访问
type Hero struct {
Name string
Ad int
level int
}
// 这里 this 不是关键字,随便起名都行
// (this Hero) 表示这个方法挂在 Hero 上
// Hero 是对象的拷贝
func (this Hero) GetName() string {
return this.Name
}
func main() {
hero := Hero{Name: "zhang3", Ad: 100}
hero.GetName()
}
// -------------
// 改成指针
func (this *Hero) SetName() string {
this.Name = "li4"
}
func main() {
hero := Hero{Name: "zhang3", Ad: 100}
hero.SetName()
}继承
go
package main
import "fmt"
type Human struct {
name string
sex string
}
func (this *Human) Eat() {
fmt.Println("Human.Eat()...")
}
//=================
type SuperMan struct {
Human //SuperMan类继承了Human类的方法
level int
}
//重定义父类的方法Eat()
func (this *SuperMan) Eat() {
fmt.Println("SuperMan.Eat()...")
}
//子类的新方法
func (this *SuperMan) Fly() {
fmt.Println("SuperMan.Fly()...")
}
func main() {
h := Human{"zhang3", "female"}
h.Eat()
var s SuperMan
s.name = "li4"
s.sex = "male"
s.level = 88
s.Walk() //父类的方法
s.Eat() //子类的方法
s.Fly() //子类的方法
}多态
interface本质是一个指针animal = &Cat{"Green"}创建 interface 变量需要传地址赋值
go
package main
import "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() //调用的就是Cat的Sleep()方法 , 多态的现象
animal = &Dog{"Yellow"}
animal.Sleep() // 调用Dog的Sleep方法,多态的现象
cat := Cat{"Green"}
dog := Dog{"Yellow"}
showAnimal(&cat)
showAnimal(&dog)
}interface
- interface{} 是万能数据类型
- arg.(string) arg 必须是一个空接口才行
go
package main
import "fmt"
//interface{}是万能数据类型
func myFunc(arg interface{}) {
fmt.Println("myFunc is called...")
fmt.Println(arg)
//interface{} 改如何区分 此时引用的底层数据类型到底是什么?
//给 interface{} 提供 “类型断言” 的机制
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)
}