zoukankan      html  css  js  c++  java
  • Go-08-函数与指针

    Go语言的函数本身可以作为值进行传递,既支持匿名函数和闭包,又能满足接口。

    函数声明

    func 函数名 (参数列表)(返回参数列表){
    // 函数体
    }
    
    func funcName(parametername type1,parametername type2  ...)(output1 type1 , utput2 type2){
    //逻辑代码
    //返回多个值
    return value1,value2
    }

    参数类型简写

    在参数列表中,如果有多个参数变量,则以逗号分隔;如果相邻变量是同类型,则可以将类型省略

    func add(a,b int){
    }

    Go语言程序中全局变量与局部变量名称可以相同,但是函数内的局部变量会被优先考虑。

    函数变量

    在Go语言中,函数也是一种类型,可以和其他类型(如int32、float等等)一样被保存在变量

    匿名函数

    Go语言支持匿名函数,即在需要使用函数时再定义函数。匿名函数没有函数名,只有函数体,函数可以作为一种类型被赋值给变量,匿名函数也往往以变量方式被传递。

    匿名函数经常被用于实现回调函数,闭包等。

    func(参数列表) (返回参数列表){
    // 函数体
    }

    1. 在定义时调匿名函数

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        func(name string){
            fmt.Println("hello",name)
        }("huahua")
    }

    2. 将匿名函数赋值给变量

    package main
    
    import "fmt"
    // 将匿名函数赋值给变量
    func main() {
        f:= func(name string) {
            fmt.Println("hello "+name)
        }
        f("sixinshuier")
    }

    3. 匿名函数用作回调函数

    package main
    
    import (
        "fmt"
        "math"
    )
    
    func main() {
        arr := []float64{1,4,36,30}
        // 求平方
        visit(arr, func(v float64) {
            v = math.Pow(v,2)
            fmt.Printf("%.2f 
    ",v)
        })
        //求平方跟
        visit(arr,func(v float64){
            v =math.Sqrt(v)
            fmt.Printf("%0.0f 
    ",v)
        })
    }
    
    func visit(list []float64, f func(float64)){
        for _,value := range list{
            f(value)
        }
    }
  • 相关阅读:
    27. Remove Element
    列表变成字典
    1. Two Sum
    CVPR2019:What and How Well You Performed? A Multitask Learning Approach to Action Quality Assessment
    959. Regions Cut By Slashes
    118. Pascal's Triangle
    loj3117 IOI2017 接线 wiring 题解
    题解 NOI2019 序列
    题解 省选联考2020 组合数问题
    题解 Educational Codeforces Round 90 (Rated for Div. 2) (CF1373)
  • 原文地址:https://www.cnblogs.com/shix0909/p/12965288.html
Copyright © 2011-2022 走看看