Menu
CoddyTech

嵌入即组合

Coddy 面向 PHP 开发者的 Go 课程的第 29 课,共 48 课。

PHP 中的扩展、父类调用和继承方法在 Go 中没有直接对应的类机制。嵌入 Go 结构体会提升其成员,但不会在内部接收者上创建被重写的虚方法。你可以用接口表达替换关系,用显式委托实现代码复用。

嵌入会通过包含的值提升字段和方法,但这不等同于类继承。你仍然可以显式指定嵌入字段。提升的方法使用其声明时指定的接收者,因此嵌入不会在该方法内部创建虚方法重写。

PHP 示例

<?php
class BaseLabel { public function text() { return 'base'; } }
class LoudLabel extends BaseLabel {
    public function text() { return parent::text() . '!'; }
}
echo (new LoudLabel())->text(), "\n";

源代码输出:

base!

Go 示例

package main
import ("fmt")
type Position struct { X int }; type Window struct { Position; Width int }
func main(){w:=Window{Position:Position{X:4},Width:8}
fmt.Println(w.X,w.Position.X)}

Go 输出:

4 4
challenge icon

挑战

简单

定义 Person{Name string},并定义嵌入 Person 且包含 Role string 的 Member。Member.Label() 返回 Name + 冒号 + Role。Solve 使用角色 editor。

实现已声明的 API;返回结果,不要打印。驱动程序会检查必需的 API,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。

在 person.go、member.go 和 exercise.go 中编写代码。main.go 包含提供的输入/输出代码,不能编辑。只保留一个扁平的 package main;不要添加第二个 main。

亲手试试

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=L(0); before0:=fmt.Sprint(a0)
must((Member{Person:Person{Name:"A"},Role:"owner"}).Label()=="A:owner","embedded API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 PHP 开发者的 Go中的所有课

自己练习: Go 在线编译器