Menu
CoddyTech

嵌入即组合

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

Rust 没有类继承,trait 和组合可以复用行为。Go 的嵌入也不是基类层次结构。提升的方法不会让嵌入的接收者动态调用外层的重写方法。最好使用显式委托和面向使用者的接口。

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

Rust 示例

fn main() {
struct Base;
impl Base { fn label(&self) -> String { String::from("base") } }
struct Child { base: Base }
impl Child { fn label(&self) -> String { self.base.label() + "!" } }
println!("{}", Child { base: Base }.label());
}

源代码输出:

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自我测试

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

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

自己练习: Go 在线编译器