zoukankan      html  css  js  c++  java
  • GO语言-基础语法:条件判断

    1. IF判断(aa.txt内容:asdfgh。bb.txt内容:12345)

    package main
    
    import (
        "io/ioutil"
        "fmt"
    )
    
    func main() {
        const filename1, filename2 = "aa.txt", "bb.txt"
    
        
        contents, err := ioutil.ReadFile(filename1) 
        if err != nil {
            fmt.Println(err)
        } else{
            fmt.Printf("%s
    ", contents)
        }
        
    
        fmt.Printf("%s
    ", contents) //打印出filename1的内容
    
        if contents, err := ioutil.ReadFile(filename2);err != nil {
            fmt.Println(err)
        } else {
            fmt.Printf("%s
    ", contents)
        }
    
        fmt.Printf("%s
    ", contents) //还是打印出filename1的内容,filename2在if条件内,跳出IF之后失效(IP内部赋值,只对本次IF有效)
    }

    打印结果;

    asdfgh
    asdfgh
    12345
    asdfgh
    [Finished in 0.6s]

     2. switch

    package main
    
    import (
        "fmt"
    )
    
    //定义函数:grade:函数名。score:传入的变量,类型是int。string:函数返回的类型。
    func grade(score int) string {
        g := ""
        switch {
        case score < 0 || score > 100:
             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"
        default://在本次switch中可以不写default,因为第一个case已经判断了所以的异常
             panic(fmt.Sprintf(
                 "Wrong score: %d", score))
        }
    
        return g
    }
    
    func main() {
        fmt.Println(grade(50),grade(60),grade(90),grade(10))
    }

    打印结果:

    F C A F
    [Finished in 0.7s]
  • 相关阅读:
    面向接口程序设计思想实践
    Block Chain Learning Notes
    ECMAScript 6.0
    Etcd Learning Notes
    Travis CI Build Continuous Integration
    Markdown Learning Notes
    SPRING MICROSERVICES IN ACTION
    Java Interview Questions Summary
    Node.js Learning Notes
    Apache Thrift Learning Notes
  • 原文地址:https://www.cnblogs.com/vijayfly/p/9474847.html
Copyright © 2011-2022 走看看