Full Stack Developer

go 基本语法(二)

2019-04-24  本文已影响1人  samtake

条件语句

if

if contents,err := ioutil.ReadFile(filename); err == nil{
    fmt.Println(string(contents))
}else{
    fmt.Println("cannot print file contents:",err)
}

switch

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"
    }
    return g
}

for

func convertToBin(n int) string{
    result := ""
    for ; n > 0; n/=2 }
        lsb := n % 2 
        result = strconv.Itoa(lsb) + result
    }
    retur result
}       
func printFile(filename string) {
    file, err := os.Open(filename)
    if err != nil{
        panic(err)
    }
        
    scanner := bufio.NewScanner(file)
    
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}   

函数

func apply(op func(int, int) int, a, b int) int {
    p := reflect.ValueOf(op).Pointer()
    opName := runtime.FuncForPC(p).name()
    fmt.Printf("call ing function %s with args " + "(%d, %d)", opName, a, b)
    
    return op(a, b)
}


func pow(a, b int) int {
    return int(math.Pow(float64(a),float64(b)))
}

fmt.Println(apply(pow, 3, 4))

or

fmt.Println(apply( func(a, b int) int { return int(math.Pow(float64(a),float64(b))) }, 3, 4))

func sum(number ...int) int {
    s := 0
    for i := range numbers {
        s += number[i]
    }
    return s
}   

sum(1,2,3,4,5)

指针

var a int = 2
var pa *int = &a
*pa = 3
fmt.Println(a)
上一篇下一篇

猜你喜欢

热点阅读