Golang物件導向_繼承

OldBoy~發表於2018-09-14
package main

import "fmt"

type Person struct {
    name string //名字
    sex  byte   //性別
    age  int    //年齡
}

type Student struct {
    Person //只有型別,沒有名字,匿名欄位,繼承了Person的成員
    id     int
    addr   string
}

func main() {
    //順序初始化
    var s1 Student = Student{Person{"mike", 'm', 18}, 1, "北京"}
    fmt.Println("s1 = ", s1)

    //自動推導型別
    s2 := Student{Person{"mike", 'm', 18}, 1, "北京"}
    //fmt.Println("s2 = ", s2)
    //%+v, 顯示更詳細
    fmt.Printf("s2 = %+v\n", s2)

    //指定成員初始化,沒有初始化的常用自動賦值為0
    s3 := Student{id: 1}
    fmt.Printf("s3 = %+v\n", s3)

    s4 := Student{Person: Person{name: "mike"}, id: 1}
    fmt.Printf("s4 = %+v\n", s4)

    //s5 := Student{"mike", 'm', 18, 1, "北京"} //err

}
s1 =  {{mike 109 18} 1 北京}
s2 = {Person:{name:mike sex:109 age:18} id:1 addr:北京}
s3 = {Person:{name: sex:0 age:0} id:1 addr:}
s4 = {Person:{name:mike sex:0 age:0} id:1 addr:}

 

相關文章