[Go] 子類 調用 父類 的 屬性、方法


package main

import (
    "fmt"
)

type A struct {
    Text string
    Name string
}

func (a *A) Say() {
    fmt.Printf("A::Say():%s\n", a.Text)
}

type B struct {
    A
    Name string
}

func (b *B) Say() {
    b.A.Say()
    fmt.Printf("B::Say():%s\n", b.Text)
}

func main() {
    b := B{A{"hello, world", "張三"}, "李四"}

    b.Say()
    fmt.Println("b的名字為:", b.Name)

    // 如果要顯示 B 的 Name 值
    fmt.Println("b的名字為:", b.A.Name)
}

輸出:

A::Say():hello, world
B::Say():hello, world
b的名字為: 李四
b的名字為: 張三

 

 

相關文章:

【Go入門教程6】struct類型(struct的匿名字段)

【Go入門教程7】面向對象(method、指針作為receiver、method繼承、method重寫)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM