Go 控制流

2017-04-25  本文已影响13人  楼上那位

if

if x:= computer(); x> 10 {

} else {

}

goto

func myFunc() {
        i := 0
    Here:   //这行的第一个词,以冒号结束作为标签
        println(i)
        i++
        goto Here   //跳转到Here去
    }

for

  sun:= 0;
 for index:= 0; index <10; index ++ {
   sum ++
}

switch

i := 0;
switch i {

case 1:

case 2,3,4:

}

函数 func

func add(a int) (int) {
   a=a+1 
return a;
}
// 一般传递的是值得copy
如果传递指针
func add(a *int) int {

 *a = *a +1;
return *a
}

defer

你可以在函数中添加多个defer语句。当函数执行到最后时,这些defer语句会按照逆序执行,最后该函数返回

func ReadWrite () bool {
 file.Open ("file")
if failureX {
file.Close()
return false
}

if failureY {
 file.Close()
return false
}
file.Close()
return true
}
// 以上是不是很繁琐

func ReadWrite() bool {

file.Open("file")
defer file.Close()
if failureX{
 return false
}
...
return true
}

函数作为值,类型

在Go中函数也是一种变量,我们可以通过type来定义它,它的类型就是所有拥有相同的参数相同的返回值的一种类型

type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])

type testInt func(int) bool // 声明了一个函数类型

struct

   package main

    import "fmt"

    type Human struct {
        name string
        age int
        weight int
    }

    type Student struct {
        Human  // 匿名字段,那么默认Student就包含了Human的所有字段
        speciality string
    }

    func main() {
        // 我们初始化一个学生
        mark := Student{Human{"Mark", 25, 120}, "Computer Science"}

        // 我们访问相应的字段
        fmt.Println("His name is ", mark.name)
        fmt.Println("His age is ", mark.age)
        fmt.Println("His weight is ", mark.weight)
        fmt.Println("His speciality is ", mark.speciality)
        // 修改对应的备注信息
        mark.speciality = "AI"
        fmt.Println("Mark changed his speciality")
        fmt.Println("His speciality is ", mark.speciality)
        // 修改他的年龄信息
        fmt.Println("Mark become old")
        mark.age = 46
        fmt.Println("His age is", mark.age)
        // 修改他的体重信息
        fmt.Println("Mark is not an athlet anymore")
        mark.weight += 60
        fmt.Println("His weight is", mark.weight)
    }

上一篇 下一篇

猜你喜欢

热点阅读