设为首页 加入收藏

TOP

Go学习笔记03-结构控制
2019-02-20 20:07:53 】 浏览:88
Tags:学习 笔记 03- 结构 控制

条件语句

条件语句用 if 关键字来判定条件,如:

    func bounded(v int) int {
        if v > 100 {
            return 100
        } else if v < 0 {
            return 0
        } else {
            return v
        }
    }

判断条件 不用圆括号 括起来

判定条件里可以赋值,赋值变量的作用域仅限于这个if语句块里。

switch语句


func grade(score int) string {
    g := ""
    switch {
    case score < 0 || score > 100:
        //当程序出错时,panic会中断程序运行
        panic(fmt.Sprintf(
            "Wrong score: %d", score))
    case score < 60:
        g = "F"
    case score < 80:
        g = "C"
    case score < 90:
        g = "B"
    case score <= 100:
        g = "A"
    }
    return g
}

Go语言中case不用break结束。
switch后可以没有条件,在case后进行条件判定。

循环语句

代码示例:


    sum := 0
    for i:= 1;i <= 100 ;i++ {
        sum += i
    }
  • for语句的条件也不需要用括号括起来
  • 可以 省略 初始条件、结束条件、递增表达式

package main

import(
    "bufio"
    "fmt"
    "os"
    "strconv"
)

func convertToBin(n int) string {
    bin := ""
    //省略初始条件,相当于while语句
    for ; n > 0; n /= 2{
        lsb := n % 2
        bin = strconv.Itoa(lsb) + bin
    }
    return bin
}

func readFile(filename string) {
    file, err := os.Open(filename)

    if err != nil{
        panic(err)
    }

    scanner := bufio.NewScanner(file)

    for scanner.Scan(){
        fmt.Println(scanner.Text())
    }
}

func main() {
    fmt.Println(convertToBin(13),
        convertToBin(5))

    readFile("file.txt")
}
  • for省略初始条件(及递增条件),相当于while语句
  • 初始条件、结束条件、递增表达式都省略是是一个死循环
  • Go中没有while语句
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用Golang搭建web服务 下一篇[Go] golang结构体成员与函数类型

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目