Remove 02.6.md spaces
This commit is contained in:
510
zh/02.6.md
510
zh/02.6.md
@@ -16,73 +16,73 @@ Go语言里面设计最精妙的应该算interface,它让面向对象,内容
|
|||||||
interface类型定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。详细的语法参考下面这个例子
|
interface类型定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。详细的语法参考下面这个例子
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
type Human struct {
|
type Human struct {
|
||||||
name string
|
name string
|
||||||
age int
|
age int
|
||||||
phone string
|
phone string
|
||||||
}
|
}
|
||||||
|
|
||||||
type Student struct {
|
type Student struct {
|
||||||
Human //匿名字段Human
|
Human //匿名字段Human
|
||||||
school string
|
school string
|
||||||
loan float32
|
loan float32
|
||||||
}
|
}
|
||||||
|
|
||||||
type Employee struct {
|
type Employee struct {
|
||||||
Human //匿名字段Human
|
Human //匿名字段Human
|
||||||
company string
|
company string
|
||||||
money float32
|
money float32
|
||||||
}
|
}
|
||||||
|
|
||||||
//Human对象实现Sayhi方法
|
//Human对象实现Sayhi方法
|
||||||
func (h *Human) SayHi() {
|
func (h *Human) SayHi() {
|
||||||
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
|
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Human对象实现Sing方法
|
// Human对象实现Sing方法
|
||||||
func (h *Human) Sing(lyrics string) {
|
func (h *Human) Sing(lyrics string) {
|
||||||
fmt.Println("La la, la la la, la la la la la...", lyrics)
|
fmt.Println("La la, la la la, la la la la la...", lyrics)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Human对象实现Guzzle方法
|
//Human对象实现Guzzle方法
|
||||||
func (h *Human) Guzzle(beerStein string) {
|
func (h *Human) Guzzle(beerStein string) {
|
||||||
fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
|
fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Employee重载Human的Sayhi方法
|
// Employee重载Human的Sayhi方法
|
||||||
func (e *Employee) SayHi() {
|
func (e *Employee) SayHi() {
|
||||||
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
|
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
|
||||||
e.company, e.phone) //此句可以分成多行
|
e.company, e.phone) //此句可以分成多行
|
||||||
}
|
}
|
||||||
|
|
||||||
//Student实现BorrowMoney方法
|
//Student实现BorrowMoney方法
|
||||||
func (s *Student) BorrowMoney(amount float32) {
|
func (s *Student) BorrowMoney(amount float32) {
|
||||||
s.loan += amount // (again and again and...)
|
s.loan += amount // (again and again and...)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Employee实现SpendSalary方法
|
//Employee实现SpendSalary方法
|
||||||
func (e *Employee) SpendSalary(amount float32) {
|
func (e *Employee) SpendSalary(amount float32) {
|
||||||
e.money -= amount // More vodka please!!! Get me through the day!
|
e.money -= amount // More vodka please!!! Get me through the day!
|
||||||
}
|
}
|
||||||
|
|
||||||
// 定义interface
|
// 定义interface
|
||||||
type Men interface {
|
type Men interface {
|
||||||
SayHi()
|
SayHi()
|
||||||
Sing(lyrics string)
|
Sing(lyrics string)
|
||||||
Guzzle(beerStein string)
|
Guzzle(beerStein string)
|
||||||
}
|
}
|
||||||
|
|
||||||
type YoungChap interface {
|
type YoungChap interface {
|
||||||
SayHi()
|
SayHi()
|
||||||
Sing(song string)
|
Sing(song string)
|
||||||
BorrowMoney(amount float32)
|
BorrowMoney(amount float32)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ElderlyGent interface {
|
type ElderlyGent interface {
|
||||||
SayHi()
|
SayHi()
|
||||||
Sing(song string)
|
Sing(song string)
|
||||||
SpendSalary(amount float32)
|
SpendSalary(amount float32)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
通过上面的代码我们可以知道,interface可以被任意的对象实现。我们看到上面的Men interface被Human、Student和Employee实现。同理,一个对象可以实现任意多个interface,例如上面的Student实现了Men和YoungChap两个interface。
|
通过上面的代码我们可以知道,interface可以被任意的对象实现。我们看到上面的Men interface被Human、Student和Employee实现。同理,一个对象可以实现任意多个interface,例如上面的Student实现了Men和YoungChap两个interface。
|
||||||
|
|
||||||
@@ -96,82 +96,82 @@ interface类型定义了一组方法,如果某个对象实现了某个接口
|
|||||||
让我们来看一下下面这个例子:
|
让我们来看一下下面这个例子:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
type Human struct {
|
import "fmt"
|
||||||
name string
|
|
||||||
age int
|
type Human struct {
|
||||||
phone string
|
name string
|
||||||
|
age int
|
||||||
|
phone string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Student struct {
|
||||||
|
Human //匿名字段
|
||||||
|
school string
|
||||||
|
loan float32
|
||||||
|
}
|
||||||
|
|
||||||
|
type Employee struct {
|
||||||
|
Human //匿名字段
|
||||||
|
company string
|
||||||
|
money float32
|
||||||
|
}
|
||||||
|
|
||||||
|
//Human实现SayHi方法
|
||||||
|
func (h Human) SayHi() {
|
||||||
|
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
|
||||||
|
}
|
||||||
|
|
||||||
|
//Human实现Sing方法
|
||||||
|
func (h Human) Sing(lyrics string) {
|
||||||
|
fmt.Println("La la la la...", lyrics)
|
||||||
|
}
|
||||||
|
|
||||||
|
//Employee重载Human的SayHi方法
|
||||||
|
func (e Employee) SayHi() {
|
||||||
|
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
|
||||||
|
e.company, e.phone)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Student struct {
|
// Interface Men被Human,Student和Employee实现
|
||||||
Human //匿名字段
|
// 因为这三个类型都实现了这两个方法
|
||||||
school string
|
type Men interface {
|
||||||
loan float32
|
SayHi()
|
||||||
}
|
Sing(lyrics string)
|
||||||
|
}
|
||||||
type Employee struct {
|
|
||||||
Human //匿名字段
|
func main() {
|
||||||
company string
|
mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
|
||||||
money float32
|
paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
|
||||||
}
|
sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
|
||||||
|
tom := Employee{Human{"Tom", 37, "222-444-XXX"}, "Things Ltd.", 5000}
|
||||||
//Human实现SayHi方法
|
|
||||||
func (h Human) SayHi() {
|
//定义Men类型的变量i
|
||||||
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
|
var i Men
|
||||||
}
|
|
||||||
|
//i能存储Student
|
||||||
//Human实现Sing方法
|
i = mike
|
||||||
func (h Human) Sing(lyrics string) {
|
fmt.Println("This is Mike, a Student:")
|
||||||
fmt.Println("La la la la...", lyrics)
|
i.SayHi()
|
||||||
}
|
i.Sing("November rain")
|
||||||
|
|
||||||
//Employee重载Human的SayHi方法
|
//i也能存储Employee
|
||||||
func (e Employee) SayHi() {
|
i = tom
|
||||||
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
|
fmt.Println("This is tom, an Employee:")
|
||||||
e.company, e.phone)
|
i.SayHi()
|
||||||
}
|
i.Sing("Born to be wild")
|
||||||
|
|
||||||
// Interface Men被Human,Student和Employee实现
|
//定义了slice Men
|
||||||
// 因为这三个类型都实现了这两个方法
|
fmt.Println("Let's use a slice of Men and see what happens")
|
||||||
type Men interface {
|
x := make([]Men, 3)
|
||||||
SayHi()
|
//这三个都是不同类型的元素,但是他们实现了interface同一个接口
|
||||||
Sing(lyrics string)
|
x[0], x[1], x[2] = paul, sam, mike
|
||||||
}
|
|
||||||
|
for _, value := range x{
|
||||||
func main() {
|
value.SayHi()
|
||||||
mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
|
|
||||||
paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
|
|
||||||
sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
|
|
||||||
tom := Employee{Human{"Tom", 37, "222-444-XXX"}, "Things Ltd.", 5000}
|
|
||||||
|
|
||||||
//定义Men类型的变量i
|
|
||||||
var i Men
|
|
||||||
|
|
||||||
//i能存储Student
|
|
||||||
i = mike
|
|
||||||
fmt.Println("This is Mike, a Student:")
|
|
||||||
i.SayHi()
|
|
||||||
i.Sing("November rain")
|
|
||||||
|
|
||||||
//i也能存储Employee
|
|
||||||
i = tom
|
|
||||||
fmt.Println("This is tom, an Employee:")
|
|
||||||
i.SayHi()
|
|
||||||
i.Sing("Born to be wild")
|
|
||||||
|
|
||||||
//定义了slice Men
|
|
||||||
fmt.Println("Let's use a slice of Men and see what happens")
|
|
||||||
x := make([]Men, 3)
|
|
||||||
//这三个都是不同类型的元素,但是他们实现了interface同一个接口
|
|
||||||
x[0], x[1], x[2] = paul, sam, mike
|
|
||||||
|
|
||||||
for _, value := range x{
|
|
||||||
value.SayHi()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
通过上面的代码,你会发现interface就是一组抽象方法的集合,它必须由其他非interface类型实现,而不能自我实现, Go通过interface实现了duck-typing:即"当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子"。
|
通过上面的代码,你会发现interface就是一组抽象方法的集合,它必须由其他非interface类型实现,而不能自我实现, Go通过interface实现了duck-typing:即"当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子"。
|
||||||
|
|
||||||
@@ -179,13 +179,13 @@ interface类型定义了一组方法,如果某个对象实现了某个接口
|
|||||||
空interface(interface{})不包含任何的method,正因为如此,所有的类型都实现了空interface。空interface对于描述起不到任何的作用(因为它不包含任何的method),但是空interface在我们需要存储任意类型的数值的时候相当有用,因为它可以存储任意类型的数值。它有点类似于C语言的void*类型。
|
空interface(interface{})不包含任何的method,正因为如此,所有的类型都实现了空interface。空interface对于描述起不到任何的作用(因为它不包含任何的method),但是空interface在我们需要存储任意类型的数值的时候相当有用,因为它可以存储任意类型的数值。它有点类似于C语言的void*类型。
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
// 定义a为空接口
|
// 定义a为空接口
|
||||||
var a interface{}
|
var a interface{}
|
||||||
var i int = 5
|
var i int = 5
|
||||||
s := "Hello world"
|
s := "Hello world"
|
||||||
// a可以存储任意类型的数值
|
// a可以存储任意类型的数值
|
||||||
a = i
|
a = i
|
||||||
a = s
|
a = s
|
||||||
```
|
```
|
||||||
一个函数把interface{}作为参数,那么他可以接受任意类型的值作为参数,如果一个函数返回interface{},那么也就可以返回任意类型的值。是不是很有用啊!
|
一个函数把interface{}作为参数,那么他可以接受任意类型的值作为参数,如果一个函数返回interface{},那么也就可以返回任意类型的值。是不是很有用啊!
|
||||||
### interface函数参数
|
### interface函数参数
|
||||||
@@ -194,41 +194,41 @@ interface的变量可以持有任意实现该interface类型的对象,这给
|
|||||||
举个例子:fmt.Println是我们常用的一个函数,但是你是否注意到它可以接受任意类型的数据。打开fmt的源码文件,你会看到这样一个定义:
|
举个例子:fmt.Println是我们常用的一个函数,但是你是否注意到它可以接受任意类型的数据。打开fmt的源码文件,你会看到这样一个定义:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
type Stringer interface {
|
type Stringer interface {
|
||||||
String() string
|
String() string
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
也就是说,任何实现了String方法的类型都能作为参数被fmt.Println调用,让我们来试一试
|
也就是说,任何实现了String方法的类型都能作为参数被fmt.Println调用,让我们来试一试
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
package main
|
package main
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Human struct {
|
type Human struct {
|
||||||
name string
|
name string
|
||||||
age int
|
age int
|
||||||
phone string
|
phone string
|
||||||
}
|
}
|
||||||
|
|
||||||
// 通过这个方法 Human 实现了 fmt.Stringer
|
// 通过这个方法 Human 实现了 fmt.Stringer
|
||||||
func (h Human) String() string {
|
func (h Human) String() string {
|
||||||
return "❰"+h.name+" - "+strconv.Itoa(h.age)+" years - ✆ " +h.phone+"❱"
|
return "❰"+h.name+" - "+strconv.Itoa(h.age)+" years - ✆ " +h.phone+"❱"
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
Bob := Human{"Bob", 39, "000-7777-XXX"}
|
Bob := Human{"Bob", 39, "000-7777-XXX"}
|
||||||
fmt.Println("This Human is : ", Bob)
|
fmt.Println("This Human is : ", Bob)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
现在我们再回顾一下前面的Box示例,你会发现Color结构也定义了一个method:String。其实这也是实现了fmt.Stringer这个interface,即如果需要某个类型能被fmt包以特殊的格式输出,你就必须实现Stringer这个接口。如果没有实现这个接口,fmt将以默认的方式输出。
|
现在我们再回顾一下前面的Box示例,你会发现Color结构也定义了一个method:String。其实这也是实现了fmt.Stringer这个interface,即如果需要某个类型能被fmt包以特殊的格式输出,你就必须实现Stringer这个接口。如果没有实现这个接口,fmt将以默认的方式输出。
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
//实现同样的功能
|
//实现同样的功能
|
||||||
fmt.Println("The biggest one is", boxes.BiggestsColor().String())
|
fmt.Println("The biggest one is", boxes.BiggestsColor().String())
|
||||||
fmt.Println("The biggest one is", boxes.BiggestsColor())
|
fmt.Println("The biggest one is", boxes.BiggestsColor())
|
||||||
```
|
```
|
||||||
注:实现了error接口的对象(即实现了Error() string的对象),使用fmt输出时,会调用Error()方法,因此不必再定义String()方法了。
|
注:实现了error接口的对象(即实现了Error() string的对象),使用fmt输出时,会调用Error()方法,因此不必再定义String()方法了。
|
||||||
### interface变量存储的类型
|
### interface变量存储的类型
|
||||||
@@ -244,44 +244,44 @@ interface的变量可以持有任意实现该interface类型的对象,这给
|
|||||||
让我们通过一个例子来更加深入的理解。
|
让我们通过一个例子来更加深入的理解。
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Element interface{}
|
type Element interface{}
|
||||||
type List [] Element
|
type List [] Element
|
||||||
|
|
||||||
type Person struct {
|
type Person struct {
|
||||||
name string
|
name string
|
||||||
age int
|
age int
|
||||||
}
|
}
|
||||||
|
|
||||||
//定义了String方法,实现了fmt.Stringer
|
//定义了String方法,实现了fmt.Stringer
|
||||||
func (p Person) String() string {
|
func (p Person) String() string {
|
||||||
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
|
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
list := make(List, 3)
|
list := make(List, 3)
|
||||||
list[0] = 1 // an int
|
list[0] = 1 // an int
|
||||||
list[1] = "Hello" // a string
|
list[1] = "Hello" // a string
|
||||||
list[2] = Person{"Dennis", 70}
|
list[2] = Person{"Dennis", 70}
|
||||||
|
|
||||||
for index, element := range list {
|
for index, element := range list {
|
||||||
if value, ok := element.(int); ok {
|
if value, ok := element.(int); ok {
|
||||||
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
|
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
|
||||||
} else if value, ok := element.(string); ok {
|
} else if value, ok := element.(string); ok {
|
||||||
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
|
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
|
||||||
} else if value, ok := element.(Person); ok {
|
} else if value, ok := element.(Person); ok {
|
||||||
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
|
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("list[%d] is of a different type\n", index)
|
fmt.Printf("list[%d] is of a different type\n", index)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
是不是很简单啊,同时你是否注意到了多个if里面,还记得我前面介绍流程时讲过,if里面允许初始化变量。
|
是不是很简单啊,同时你是否注意到了多个if里面,还记得我前面介绍流程时讲过,if里面允许初始化变量。
|
||||||
|
|
||||||
@@ -291,45 +291,45 @@ interface的变量可以持有任意实现该interface类型的对象,这给
|
|||||||
最好的讲解就是代码例子,现在让我们重写上面的这个实现
|
最好的讲解就是代码例子,现在让我们重写上面的这个实现
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Element interface{}
|
type Element interface{}
|
||||||
type List [] Element
|
type List [] Element
|
||||||
|
|
||||||
type Person struct {
|
type Person struct {
|
||||||
name string
|
name string
|
||||||
age int
|
age int
|
||||||
}
|
}
|
||||||
|
|
||||||
//打印
|
//打印
|
||||||
func (p Person) String() string {
|
func (p Person) String() string {
|
||||||
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
|
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
list := make(List, 3)
|
list := make(List, 3)
|
||||||
list[0] = 1 //an int
|
list[0] = 1 //an int
|
||||||
list[1] = "Hello" //a string
|
list[1] = "Hello" //a string
|
||||||
list[2] = Person{"Dennis", 70}
|
list[2] = Person{"Dennis", 70}
|
||||||
|
|
||||||
for index, element := range list{
|
for index, element := range list{
|
||||||
switch value := element.(type) {
|
switch value := element.(type) {
|
||||||
case int:
|
case int:
|
||||||
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
|
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
|
||||||
case string:
|
case string:
|
||||||
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
|
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
|
||||||
case Person:
|
case Person:
|
||||||
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
|
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
|
||||||
default:
|
default:
|
||||||
fmt.Println("list[%d] is of a different type", index)
|
fmt.Println("list[%d] is of a different type", index)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
这里有一点需要强调的是:`element.(type)`语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用`comma-ok`。
|
这里有一点需要强调的是:`element.(type)`语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用`comma-ok`。
|
||||||
|
|
||||||
@@ -339,33 +339,33 @@ Go里面真正吸引人的是它内置的逻辑语法,就像我们在学习Str
|
|||||||
我们可以看到源码包container/heap里面有这样的一个定义
|
我们可以看到源码包container/heap里面有这样的一个定义
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
type Interface interface {
|
type Interface interface {
|
||||||
sort.Interface //嵌入字段sort.Interface
|
sort.Interface //嵌入字段sort.Interface
|
||||||
Push(x interface{}) //a Push method to push elements into the heap
|
Push(x interface{}) //a Push method to push elements into the heap
|
||||||
Pop() interface{} //a Pop elements that pops elements from the heap
|
Pop() interface{} //a Pop elements that pops elements from the heap
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
我们看到sort.Interface其实就是嵌入字段,把sort.Interface的所有method给隐式的包含进来了。也就是下面三个方法:
|
我们看到sort.Interface其实就是嵌入字段,把sort.Interface的所有method给隐式的包含进来了。也就是下面三个方法:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
type Interface interface {
|
type Interface interface {
|
||||||
// Len is the number of elements in the collection.
|
// Len is the number of elements in the collection.
|
||||||
Len() int
|
Len() int
|
||||||
// Less returns whether the element with index i should sort
|
// Less returns whether the element with index i should sort
|
||||||
// before the element with index j.
|
// before the element with index j.
|
||||||
Less(i, j int) bool
|
Less(i, j int) bool
|
||||||
// Swap swaps the elements with indexes i and j.
|
// Swap swaps the elements with indexes i and j.
|
||||||
Swap(i, j int)
|
Swap(i, j int)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
另一个例子就是io包下面的 io.ReadWriter ,它包含了io包下面的Reader和Writer两个interface:
|
另一个例子就是io包下面的 io.ReadWriter ,它包含了io包下面的Reader和Writer两个interface:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
// io.ReadWriter
|
// io.ReadWriter
|
||||||
type ReadWriter interface {
|
type ReadWriter interface {
|
||||||
Reader
|
Reader
|
||||||
Writer
|
Writer
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
### 反射
|
### 反射
|
||||||
Go语言实现了反射,所谓反射就是能检查程序在运行时的状态。我们一般用到的包是reflect包。如何运用reflect包,官方的这篇文章详细的讲解了reflect包的实现原理,[laws of reflection](http://golang.org/doc/articles/laws_of_reflection.html)
|
Go语言实现了反射,所谓反射就是能检查程序在运行时的状态。我们一般用到的包是reflect包。如何运用reflect包,官方的这篇文章详细的讲解了reflect包的实现原理,[laws of reflection](http://golang.org/doc/articles/laws_of_reflection.html)
|
||||||
@@ -373,38 +373,38 @@ Go语言实现了反射,所谓反射就是能检查程序在运行时的状态
|
|||||||
使用reflect一般分成三步,下面简要的讲解一下:要去反射是一个类型的值(这些值都实现了空interface),首先需要把它转化成reflect对象(reflect.Type或者reflect.Value,根据不同的情况调用不同的函数)。这两种获取方式如下:
|
使用reflect一般分成三步,下面简要的讲解一下:要去反射是一个类型的值(这些值都实现了空interface),首先需要把它转化成reflect对象(reflect.Type或者reflect.Value,根据不同的情况调用不同的函数)。这两种获取方式如下:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
t := reflect.TypeOf(i) //得到类型的元数据,通过t我们能获取类型定义里面的所有元素
|
t := reflect.TypeOf(i) //得到类型的元数据,通过t我们能获取类型定义里面的所有元素
|
||||||
v := reflect.ValueOf(i) //得到实际的值,通过v我们获取存储在里面的值,还可以去改变值
|
v := reflect.ValueOf(i) //得到实际的值,通过v我们获取存储在里面的值,还可以去改变值
|
||||||
```
|
```
|
||||||
转化为reflect对象之后我们就可以进行一些操作了,也就是将reflect对象转化成相应的值,例如
|
转化为reflect对象之后我们就可以进行一些操作了,也就是将reflect对象转化成相应的值,例如
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
tag := t.Elem().Field(0).Tag //获取定义在struct里面的标签
|
tag := t.Elem().Field(0).Tag //获取定义在struct里面的标签
|
||||||
name := v.Elem().Field(0).String() //获取存储在第一个字段里面的值
|
name := v.Elem().Field(0).String() //获取存储在第一个字段里面的值
|
||||||
```
|
```
|
||||||
获取反射值能返回相应的类型和数值
|
获取反射值能返回相应的类型和数值
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
var x float64 = 3.4
|
var x float64 = 3.4
|
||||||
v := reflect.ValueOf(x)
|
v := reflect.ValueOf(x)
|
||||||
fmt.Println("type:", v.Type())
|
fmt.Println("type:", v.Type())
|
||||||
fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
|
fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
|
||||||
fmt.Println("value:", v.Float())
|
fmt.Println("value:", v.Float())
|
||||||
```
|
```
|
||||||
最后,反射的话,那么反射的字段必须是可修改的,我们前面学习过传值和传引用,这个里面也是一样的道理。反射的字段必须是可读写的意思是,如果下面这样写,那么会发生错误
|
最后,反射的话,那么反射的字段必须是可修改的,我们前面学习过传值和传引用,这个里面也是一样的道理。反射的字段必须是可读写的意思是,如果下面这样写,那么会发生错误
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
var x float64 = 3.4
|
var x float64 = 3.4
|
||||||
v := reflect.ValueOf(x)
|
v := reflect.ValueOf(x)
|
||||||
v.SetFloat(7.1)
|
v.SetFloat(7.1)
|
||||||
```
|
```
|
||||||
如果要修改相应的值,必须这样写
|
如果要修改相应的值,必须这样写
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
var x float64 = 3.4
|
var x float64 = 3.4
|
||||||
p := reflect.ValueOf(&x)
|
p := reflect.ValueOf(&x)
|
||||||
v := p.Elem()
|
v := p.Elem()
|
||||||
v.SetFloat(7.1)
|
v.SetFloat(7.1)
|
||||||
```
|
```
|
||||||
上面只是对反射的简单介绍,更深入的理解还需要自己在编程中不断的实践。
|
上面只是对反射的简单介绍,更深入的理解还需要自己在编程中不断的实践。
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user