修复代码的格式
This commit is contained in:
60
2.6.md
60
2.6.md
@@ -234,44 +234,44 @@ interface的变量可以持有任意实现该interface类型的对象,这给
|
|||||||
|
|
||||||
让我们通过一个例子来更加深入的理解。
|
让我们通过一个例子来更加深入的理解。
|
||||||
|
|
||||||
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.Println("list[%d] is of a different type", index)
|
fmt.Println("list[%d] is of a different type", index)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
是不是很简单啊,同时你是否注意到了多个ifs里面,还记得我前面介绍流程里面讲过,if里面允许初始化变量。
|
是不是很简单啊,同时你是否注意到了多个ifs里面,还记得我前面介绍流程里面讲过,if里面允许初始化变量。
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user