Go语言学习笔记(十一)
一.继承
嵌套匿名结构体
type Goods struct {
Name string
Price int
}
type Book struct {
Goods
Write string
}
继承的深入讨论
package main
import (
"fmt"
)
type A struct {
Name string
age int
}
func (a *A) Sayok() {
fmt.Println("A hello",a.Name)
}
func (a *A) hello() {
fmt.Println("A hello",a.Name)
}
type B struct{
A
}
func main() {
var b B
b.A.Name = "tom"
b.A.age = 19
b.A.Sayok()
b.A.hello()
}
赋值
package main
import (
"fmt"
)
type Goods struct {
name string
price int
}
type Brand struct {
Name string
address string
}
type TV struct{
Goods
Brand
}
tv :=TV{ Goods{"电视机",500}, Brand{"haier","shandong"}}
tv2 := TV{
Goods{
prince : 500,
name :"电视机2",
},
Brand{
Name : "xiapu",
address : "peking",
},
}
fmt.Println("tv",tv)
fmt.Println("tv2",tv2)
二.接口
type helloworld interface {
Helloworld() string
}
type Hello struct {
Message string
}
func (h *hello) Hello() string {
fmt.Println("hello world")
1.Go 语言中接口的实现都是隐式的,我们只需要实现 Hello() string 方法就实现了 hello 接口
2.空接口就是不包含任何方法的接口。正因为如此,所有的类型都实现了空接口。虽然空接口起不到任何作用,但是空接口在需要存储任何类型数值的时候非常有用。
由一个类型实现多个接口
package main
import (
"fmt"
)
type Students interface {
ReturnName() string
}
type Race interface {
Returnrace() string
}
type Student struct {
grade float64
}
func (s Student) ReturnName() string {
return s.Name
}
func (s Student) Returnrace() string {
return "男"
}
接口的嵌套
先定义写入器(Writer)、关闭器(Closer)和写入关闭器(WriteCloser)三 个接口
type Writer interface {
Write(p []byte) (n int, err error)
}
type Closer interface {
Close() error
}
type WriteCloser interface {
Writer
Closer
}
代码说明如下:
第 1 行定义了写入器(Writer),如这个接口较为常用,常用于 I/O 设备的数据写入。
第 5 行定义了关闭器(Closer),如有非托管内存资源的对象,需要用关闭的方法来实现资源释放。
第 9 行定义了写入关闭器(WriteCloser),这个接口由 Writer 和 Closer 两个接口嵌入。也就是说,WriteCloser 同时拥有了 Writer 和 Closer 的特性。
参考
三.接口与继承
接口可以算是对于继承的一种补充
```go
package main
import(
"fmt"
)
type Monkey struct{
Name string
}
func (this *Monkey) climbing() {
fmt.Println(this.Name,"生来会爬树")
}
type LittleMonkey struct{
Monkey
}
func main() {
monkey := LittleMonkey{
Monkey{
Name : "悟空",
},
}
monkey.climbing()
}
利用接口对对其进行一些的补充
```go
package main
import(
"fmt"
)
type Monkey struct{
Name string
}
func (this *Monkey) climbing() {
fmt.Println(this.Name,"生来会爬树")
}
type LittleMonkey struct{
Monkey
}
func main() {
monkey := LittleMonkey{
Monkey{
Name : "悟空",
},
}
monkey.climbing()
}