From a249ee0e768754168ee70710a7092ae2e9d76350 Mon Sep 17 00:00:00 2001 From: xiemengjun Date: Sun, 18 Nov 2012 22:50:03 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BB=A3=E7=A0=81=E7=9A=84?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2.6.md | 60 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/2.6.md b/2.6.md index a4c9b8c7..85f0ed93 100644 --- a/2.6.md +++ b/2.6.md @@ -234,44 +234,44 @@ interface的变量可以持有任意实现该interface类型的对象,这给 让我们通过一个例子来更加深入的理解。 - 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 + } - //定义了String方法,实现了fmt.Stringer - func (p Person) String() string { - return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)" - } + //定义了String方法,实现了fmt.Stringer + 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 { - if value, ok := element.(int); ok { - fmt.Printf("list[%d] is an int and its value is %d\n", index, value) - } else if value, ok := element.(string); ok { - fmt.Printf("list[%d] is a string and its value is %s\n", index, value) - } else if value, ok := element.(Person); ok { - fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) - } else { - fmt.Println("list[%d] is of a different type", index) + for index, element := range list { + if value, ok := element.(int); ok { + fmt.Printf("list[%d] is an int and its value is %d\n", index, value) + } else if value, ok := element.(string); ok { + fmt.Printf("list[%d] is a string and its value is %s\n", index, value) + } else if value, ok := element.(Person); ok { + fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) + } else { + fmt.Println("list[%d] is of a different type", index) + } } } - } 是不是很简单啊,同时你是否注意到了多个ifs里面,还记得我前面介绍流程里面讲过,if里面允许初始化变量。