Go语言之面向对象

Jackey Golang 2,525 次浏览 , 没有评论

面向对象

  1. // main
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. )
  7.  
  8. /*func compare(a, b int) bool {
  9. return a < b
  10. }*/
  11.  
  12. type Point struct {
  13. px float32
  14. py float32
  15. }
  16.  
  17. func (point *Point) setXY(px, py float32) {
  18. point.px = px
  19. point.py = py
  20. }
  21.  
  22. func (point *Point) getXY() (float32, float32) {
  23. return point.px, point.py
  24. }
  25.  
  26. type Integer struct {
  27. value int
  28. }
  29.  
  30. func (a Integer) compare(b Integer) bool {
  31. return a.value < b.value
  32. }
  33.  
  34. func main() {
  35. //初始化
  36. point := new(Point)
  37. point.setXY(1.23, 4.56)
  38. px, py := point.getXY()
  39. fmt.Print(px, py)
  40. }

类型和作用在它上面定义的方法必须在同一个包里定义,这就是为什么不能在 int、float 或类似这些的类型上定义方法。

继承

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type Person struct {
  6. name string
  7. age int
  8. }
  9.  
  10. func (person Person) getNameAndAge() (string, int) {
  11. return person.name, person.age
  12. }
  13.  
  14. type Student struct {
  15. Person
  16. speciality string
  17. }
  18.  
  19. func (student Student) getSpeciality() string {
  20. return student.speciality
  21. }
  22.  
  23. type Animal interface {
  24. Fly()
  25. Run()
  26. }
  27.  
  28. type Animal2 interface {
  29. Fly()
  30. }
  31.  
  32. type Bird struct {
  33. }
  34.  
  35. func (bird Bird) Fly() {
  36. fmt.Println("Bird is flying!!!!")
  37. }
  38.  
  39. func (bird Bird) Run() {
  40. fmt.Println("Bird is running!!!!")
  41. }
  42.  
  43. func main() {
  44. /*student := new(Student)
  45. student.name = "zhangsan"
  46. student.age = 26
  47. name, age := student.getNameAndAge()
  48.  
  49. speciality := student.getSpeciality()
  50.  
  51. fmt.Println(name, age)*/
  52. /*var animal Animal
  53. var animal2 Animal2
  54.  
  55. bird := new(Bird)
  56. animal = bird
  57. animal2 = animal
  58. //
  59. animal2.Fly()*/
  60. //animal = bird //把类实例直接赋值给接口
  61. //animal2 = bird
  62.  
  63. //animal2.Fly()
  64. //animal.Fly()
  65. //animal.Run()
  66.  
  67. var v1 interface{}
  68. v1 = "zhangsan"
  69.  
  70. switch v1.(type) {
  71. case int:
  72. case float32:
  73. case float64:
  74. fmt.Println("this is float64")
  75. case string:
  76. fmt.Println("this is string")
  77. }
  78. }

在Go语言中,一个类只需要实现了接口要求的所有函数,我们就说这个类实现了该接口。

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go