码迷,mamicode.com
首页 > 其他好文 > 详细

[Go] 子类 调用 父类 的 属性、方法

时间:2017-08-04 12:00:19      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:www.   type   import   .text   get   文章   html   面向   htm   

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重写)

[Go] 子类 调用 父类 的 属性、方法

标签:www.   type   import   .text   get   文章   html   面向   htm   

原文地址:http://www.cnblogs.com/phpgo/p/7284232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!