zoukankan      html  css  js  c++  java
  • 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
    */
    
  • 相关阅读:
    python pyinotify模块详解
    lastpass密码管理工具使用教程
    MAMP 环境下安装Redis扩展
    SourceTree使用方法
    Mac securecrt 破解
    Memcache 安装
    Warning: setcookie() expects parameter 3 to be long, string given
    SQLSTATE[HY000] [2002] Connection refused
    插件管理无法访问
    光栅化渲染器
  • 原文地址:https://www.cnblogs.com/michealjy/p/13090121.html
Copyright © 2011-2022 走看看