修复格式
This commit is contained in:
68
2.6.md
68
2.6.md
@@ -273,52 +273,52 @@ interface的变量可以持有任意实现该interface类型的对象,这给
|
||||
}
|
||||
}
|
||||
|
||||
是不是很简单啊,同时你是否注意到了多个ifs里面,还记得我前面介绍流程里面讲过,if里面允许初始化变量。
|
||||
是不是很简单啊,同时你是否注意到了多个ifs里面,还记得我前面介绍流程里面讲过,if里面允许初始化变量。
|
||||
|
||||
也许你注意到了,我们断言的类型越多,那么ifelse也就越多,所以才引出了下面要介绍的switch。
|
||||
也许你注意到了,我们断言的类型越多,那么ifelse也就越多,所以才引出了下面要介绍的switch。
|
||||
- switch测试
|
||||
|
||||
最好的讲解就是代码例子,现在让我们重写上面的这个实现
|
||||
最好的讲解就是代码例子,现在让我们重写上面的这个实现
|
||||
|
||||
package main
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Element interface{}
|
||||
type List [] Element
|
||||
type Element interface{}
|
||||
type List [] Element
|
||||
|
||||
type Person struct {
|
||||
name string
|
||||
age int
|
||||
}
|
||||
type Person struct {
|
||||
name string
|
||||
age int
|
||||
}
|
||||
|
||||
//打印
|
||||
func (p Person) String() string {
|
||||
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
|
||||
}
|
||||
//打印
|
||||
func (p Person) String() string {
|
||||
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
|
||||
}
|
||||
|
||||
func main() {
|
||||
list := make(List, 3)
|
||||
list[0] = 1 //an int
|
||||
list[1] = "Hello" //a string
|
||||
list[2] = Person{"Dennis", 70}
|
||||
func main() {
|
||||
list := make(List, 3)
|
||||
list[0] = 1 //an int
|
||||
list[1] = "Hello" //a string
|
||||
list[2] = Person{"Dennis", 70}
|
||||
|
||||
for index, element := range list{
|
||||
switch value := element.(type) {
|
||||
case int:
|
||||
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
|
||||
case string:
|
||||
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
|
||||
case Person:
|
||||
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
|
||||
default:
|
||||
fmt.Println("list[%d] is of a different type", index)
|
||||
for index, element := range list{
|
||||
switch value := element.(type) {
|
||||
case int:
|
||||
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
|
||||
case string:
|
||||
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
|
||||
case Person:
|
||||
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
|
||||
default:
|
||||
fmt.Println("list[%d] is of a different type", index)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
这里有一点需要强调的是:`element.(type)`语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用`comma-ok`。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user