image.png


    strcut简介:

    go语言中是没有类的,但是并不能说go语言不能支持面向对象编程,python或java中使用类来实现封装,继承,等特性。在go语言中是没有继承这一概念的。替代的方案是使用组合,结构体是实现组合的载体。通过结构体的嵌入,可以将不同结构体组合在一起,从而将每个结构体自带的方法都加入到一个方法集。


    自定义strcut的两种方法

    1. var myStruct struct {//方法一
    2. number float64
    3. word string
    4. toggle bool
    5. }
    6. type car struct {//方法二
    7. description string
    8. cost int
    9. }
    10. myStruct.number = 3.14
    11. var porsche car
    12. porsche.description = "mycar"
    13. porsche.cost = 100

    类型遮盖

    1. package main
    2. type car struct {
    3. description string
    4. cost int
    5. }
    6. func main() {
    7. myStruct.number = 3.14
    8. var car car//类型遮盖
    9. car.description = "mycar"
    10. car.cost = 100
    11. var car2 car
    12. //类型遮盖问题,自定义变量名car覆盖了自定义的类型变量car
    13. //在实际应用种,类型一般是在其它程序包种导入,变量名为大写eg:Car
    14. //而自定义变量一般为小写car
    15. }

    传递struct变量指针

    在第一篇中,提到过,结构体是值类型数据,传入函数时,是以传值的方式传入的。即将结构体的值得一份拷贝传入了函数,在函数中修改值,并不会改变结构体得值。对所以要想令函数改变结构体得值应该使用指针,传递指针,也可以避免参数拷贝造成的内存浪费

    1. package main
    2. import "fmt"
    3. type subsciber struct {
    4. name string
    5. rate float64
    6. active bool
    7. }
    8. func applyDiscount(s *subsciber) {
    9. s.rate = 4.99
    10. //更新struct变量的字段
    11. }
    12. func main() {
    13. var s subsciber
    14. applyDiscount(&s)
    15. //传入变量s的地址
    16. fmt.Println(s.rate)
    17. }

    结构体的指针访问字段
    image.png


    将struct作为字段—字段嵌入

    1. package magazine
    2. type Subsciber struct {
    3. Name string
    4. Rate float64
    5. Active bool
    6. HomeAddress Address
    7. //需要在多个结构体中重用的字段
    8. //建议设置为结构体字段
    9. }
    10. type Employee struct {
    11. Name string
    12. Salary float64
    13. HomeAddress Address
    14. }
    15. type Address struct {
    16. Street string
    17. City string
    18. State string
    19. PostCode string
    20. }
    21. func main() {
    22. address := Address{Street: "xinda", City: "xian", State: "shanxi", PostCode: "710600"}
    23. subscriber1 := Subsciber{Name: "uni"}
    24. subscriber1.HomeAddress = address
    25. fmt.Println(subscriber1.HomeAddress)
    26. employee := Employee{Name: "uni"}
    27. employee.HomeAddress.City = "beijing"
    28. employee.HomeAddress.PostCode = "8900"
    29. }

    匿名strcut字段

    image.png


    嵌入struct

    匿名struct其实是嵌入式struct,真实的访问方式如下:
    image.png