且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GO语言练习:组合的用法

更新时间:2022-09-16 17:46:44

1、代码

GO语言练习:组合的用法
 1 package main
 2 
 3 import "fmt"
 4 
 5 type Base struct {
 6     Name string
 7 }
 8 
 9 func (base * Base) Foo() {
10     fmt.Println("Base Foo : ", base.Name)
11 }
12 
13 func (base * Base) Bar() {
14     fmt.Println("Base Bar : ", base.Name)
15 }
16 
17 type Foo struct {
18     Base
19     a int 
20 }
21 
22 func (foo * Foo) Bar() {
23     foo.Base.Bar()
24     fmt.Println("\tFoo Bar : ", foo.Name)
25 }
26 
27 func main() {
28     var str string = "hello world"
29 
30     base := &Base{str}
31     base.Foo()
32 
33     str = "Ni hao"
34     foo := &Foo{Base{str}, 0}
35     foo.Bar()
36     foo.Foo()
37 }
GO语言练习:组合的用法

2、运行

GO语言练习:组合的用法
$ go run combination.go 
Base Foo :  hello world
Base Bar :  Ni hao
    Foo Bar :  Ni hao
Base Foo :  Ni hao
GO语言练习:组合的用法

 


本文转自郝峰波博客园博客,原文链接:http://www.cnblogs.com/fengbohello/p/4625467.html,如需转载请自行联系原作者