• GO基础知识(条件判断、循环)


    条件判断

    //if else
    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    	if num := 10; num % 2 == 0 { //checks if number is even
    		fmt.Println(num,"is even")
    	}  else {
    		fmt.Println(num,"is odd")
    	}
    	fmt.Println(num)//会报错,因为num的作用域只在if else语句中
    }
    
    
    
    //if  else if.... else
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 99
        if num <= 50 {
            fmt.Println("number is less than or equal to 50")
        } else if num >= 51 && num <= 100 {
            fmt.Println("number is between 51 and 100")
        } else {
            fmt.Println("number is greater than 100")
        }
    
    }
    
    //else需要放在if}的同一行
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 10
        if num % 2 == 0 { //checks if number is even
            fmt.Println("the number is even") 
        }  
        else {
            fmt.Println("the number is odd")
        }
    } //报错:main.go:12:5: syntax error: unexpected else, expecting }
    

    循环

    //go语言中只有唯一的循环语句for
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        for i := 1; i <= 10; i++ {
            fmt.Printf(" %d",i)
        }
    }
    
    
    //break,跳出循环
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        for i := 1; i <= 10; i++ {
            if i > 5 {
                break //loop is terminated if i > 5
            }
            fmt.Printf("%d ", i)
        }
        fmt.Printf("
    line after for loop")
    }
    /*
    输出
    1 2 3 4 5  
    line after for loop
    */
    
    
    //continue,跳出当前循环,执行下一次循环
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        for i := 1; i <= 10; i++ {
            if i%2 == 0 {
                continue
            }
            fmt.Printf("%d ", i)
        }
    }
    /*输出结果
    1 3 5 7 9
    */
    
  • 相关阅读:
    走势图通用写法
    配置文件通配符的问题
    jvm排查工具
    有趣的linux命令
    jQuery框架
    jQuery常见案例
    页面布局之--Font Awesome+导航
    页面布局之--导航栏功能
    页面布局之--内容区域的左右分居
    Dom,查找标签和操作标签
  • 原文地址:https://www.cnblogs.com/michealjy/p/13090121.html
Copyright © 2020-2023  润新知