面向对象
- // main
- package main
-
- import (
- "fmt"
- )
-
- /*func compare(a, b int) bool {
- return a < b
- }*/
-
- type Point struct {
- px float32
- py float32
- }
-
- func (point *Point) setXY(px, py float32) {
- point.px = px
- point.py = py
- }
-
- func (point *Point) getXY() (float32, float32) {
- return point.px, point.py
- }
-
- type Integer struct {
- value int
- }
-
- func (a Integer) compare(b Integer) bool {
- return a.value < b.value
- }
-
- func main() {
- //初始化
- point := new(Point)
- point.setXY(1.23, 4.56)
- px, py := point.getXY()
- fmt.Print(px, py)
- }
类型和作用在它上面定义的方法必须在同一个包里定义,这就是为什么不能在 int、float 或类似这些的类型上定义方法。
继承
- package main
-
- import "fmt"
-
- type Person struct {
- name string
- age int
- }
-
- func (person Person) getNameAndAge() (string, int) {
- return person.name, person.age
- }
-
- type Student struct {
- Person
- speciality string
- }
-
- func (student Student) getSpeciality() string {
- return student.speciality
- }
-
- type Animal interface {
- Fly()
- Run()
- }
-
- type Animal2 interface {
- Fly()
- }
-
- type Bird struct {
- }
-
- func (bird Bird) Fly() {
- fmt.Println("Bird is flying!!!!")
- }
-
- func (bird Bird) Run() {
- fmt.Println("Bird is running!!!!")
- }
-
- func main() {
- /*student := new(Student)
- student.name = "zhangsan"
- student.age = 26
- name, age := student.getNameAndAge()
-
- speciality := student.getSpeciality()
-
- fmt.Println(name, age)*/
- /*var animal Animal
- var animal2 Animal2
-
- bird := new(Bird)
- animal = bird
- animal2 = animal
- //
- animal2.Fly()*/
- //animal = bird //把类实例直接赋值给接口
- //animal2 = bird
-
- //animal2.Fly()
- //animal.Fly()
- //animal.Run()
-
- var v1 interface{}
- v1 = "zhangsan"
-
- switch v1.(type) {
- case int:
- case float32:
- case float64:
- fmt.Println("this is float64")
- case string:
- fmt.Println("this is string")
- }
- }
在Go语言中,一个类只需要实现了接口要求的所有函数,我们就说这个类实现了该接口。