zoukankan      html  css  js  c++  java
  • Golang

    Golang - 函数

    1. 自定义函数

    函数声明格式

    func 函数名( [参数列表] ) [返回值类型列表] {
       函数体
    }
    

    所有类型

    //package 声明开头表示代码所属包
    package main
    
    import "fmt"
    
    
    //无参无返回值
    func test01(){
    	fmt.Println("三无产品")
    }
    
    
    //有参无返回值
    func test02(v1 int, v2 int){
    	fmt.Println(v1, v2)
    }
    
    func test022(v1, v2 int)  {
    	fmt.Println(v1, v2)
    }
    
    
    //有不定参数无返回值
    func test03(args ...int){
    	//遍历
    	for _,n := range  args{
    		fmt.Println(n)
    	}
    }
    
    func main() {
    	test03(1, 2, 3)
    }
    
    
    //无参有返回值
    func test04()(a int, str string){
    	a = 666
    	str = "沙雕"
    	return
    }
    
    
    //有参有返回值
    func test05(num1 int, num2 int)(min int, max int){
    	if num1 > num2{
    		min = num2
    		max = num1
    	}else{
    		max = num2
    		min = num1
    	}
    	return
    }
    

    练习: 分别通过循环和递归函数,计算1+2+3……+100

    //package 声明开头表示代码所属包
    package main
    
    import "fmt"
    
    //第一种
    func test011() int {
    	i := 1
    	sum := 0
    	for i = 1; i <= 100; i++ {
    		sum += i
    	}
    	return sum
    }
    
    //第二种
    func test012(num int) int {
    	if num == 1 {
    		return 1
    	}
    	return num + test012(num-1)
    }
    func main() {
    	//fmt.Println(test011())
    	fmt.Println(test012(100))
    }
    

    2. defer关键字

    • d- efer用于延迟一个函数或者方法的执行

    • defer语句经常被用于处理成对的操作,如打开、关闭、连接、断开连接、加锁、释放锁

    • 通过defer机制,不论函数逻辑多复杂,都能保证在任何执行路径下,资源被释放

    • 释放资源的defer应该直接跟在请求资源的语句后,以免忘记释放资源

      //package 声明开头表示代码所属包
      package main
      
      import "fmt"
      
      func main() {
      	defer fmt.Println("defer语句")
      	fmt.Println("打酱油")
      }
      
      //打酱油
      //defer语句
      

    3. 多个defer执行顺序

    //package 声明开头表示代码所属包
    package main
    
    import "fmt"
    
    func test99(x int){
    	fmt.Println(100 / x)
    }
    
    func main() {
    	defer fmt.Println("1号门")
    	defer fmt.Println("2号门")
    	test99(0)
    	defer fmt.Println("3号门")
    }
    
    
    //2号门
    //1号门
    //panic: runtime error: integer divide by zero
    //
    //goroutine 1 [running]:
    //main.test99(0x0)
    //D:/awesomeProject/first.go:7 +0xb3
    //main.main()
    //D:/awesomeProject/first.go:13 +0xed
  • 相关阅读:
    十七、oracle 权限
    九、oracle 事务
    十六、oracle 索引
    十九、oracle pl/sql简介
    二十二、oracle pl/sql分类二 函数
    通过HttpURLConnection模拟post表单提交
    八、oracle 分页
    二十一、oracle pl/sql分类一 存储过程
    xStream框架操作XML、JSON
    二十、oracle pl/sql基础
  • 原文地址:https://www.cnblogs.com/konghui/p/10703591.html
Copyright © 2011-2022 走看看