zoukankan      html  css  js  c++  java
  • 13_函数的基本使用简介

    go语言中,函数一些规则:

    /*函数名规定首字母大写为public,首字母小写为private
    public允许被其他函数调用
      函数的关键字是func
    格式为:
    	func FunName(参数列表)(返回值列表){
    		//函数体
    		return //返回值
    	}
    
    
    */


    例如:
    package main
    
    
    import "fmt"
    //无参无返回值,返回值列表为空,可以不写
    func Print() {
    	fmt.Println("Hello func,it's very good!!!")
    
    
    }
    
    
    //无参,一个返回值,返回值列表可以不加括号
    func Service() string {
    	good := "good"
    	return good
    
    
    }
    
    
    //普通参数列表,多个参数(参数类型一样)
    func Print1(a, b, c int) {
    	fmt.Printf("a=%d,b=%d,c=%d
    ", a, b, c)
    
    
    }
    
    
    //普通参数列表,参数类型不一样(只能分开写,推荐分开写,结构更清晰)
    func Print2(a int, b string, c float64) {
    	fmt.Printf("a=%d,b=%s,c=%f", a, b, c)
    }
    
    
    //不定参数列表
    func Print3(args ...int) {
    	//使用for循环进行遍历输出,range迭代
    	//range迭代会有两个值,一个是索引值,一个是索引位置值
    	for i, data := range args {
    		fmt.Printf("i=%v,data=%v
    ", i, data)
    	}
    	//另一种输出方法
    	fmt.Println("另一种不定参数列表遍历-")
    	for i := 0; i < len(args); i++ {
    		fmt.Printf("args[%d]=%d
    ", i, args[i])
    	}
    }
    
    
    //不定参数的传递
    //...type  不定参数类型
    func Test(args ...int) {
    	Print3(args...)
    }
    
    
    //切片传入部分参数
    func Test1(args ...int) {
    	//后面三个点不能忘记
    	Print3(args[2:]...)
    }
    
    
    //无参多个返回值,如果多个返回值类型一样,也可以只写一个类型
    func Print4() (a int, score string) {
    	a, score = 1, "90"
    	return
    }
    
    
    //多个参数,多个返回值
    func MaxMin(a, b int) (max, min int) {
    	if a > b {
    		max = a
    		min = b
    	} else {
    		max, min = b, a
    	}
    	return //不能少,默认返回返回参数的值
    }
    
    
    func main() {
    	fmt.Println("无参无返回值---")
    	Print()
    	fmt.Println("无参一个返回值--")
    	commmet := Service()
    	fmt.Println("你的服务质量为:", commmet)
    	fmt.Println("普通参数列表无返回值--")
    	Print1(1, 2, 3)
    	Print2(1, "优秀", 97.8)
    	fmt.Println("不定参数列表--")
    	Print3(1, 2, 3, 4)
    	fmt.Println("不定参数列表的传递--")
    	Test(5, 6, 7, 8)
    	Test1(5, 6, 7, 8)
    	fmt.Println("多个返回值--")
    	r, s := Print4()
    	fmt.Printf("r=%d,s=%s
    ", r, s)
    
    
    	fmt.Println("多个返回值,多个参数--")
    	m, n := MaxMin(1, 2)
    	fmt.Printf("最大值为 %d,最小值为%d", m, n)
    
    
    }


    运行结果:

                                         

    每天的价值就是不停息的前进!!!
  • 相关阅读:
    初识CC_MVPMatrix
    opengl启动过程
    http协议
    sockt套接字编程
    lua元表
    Codeforces 1203F1 Complete the Projects (easy version)
    CodeForces 1200E Compress Words
    CodeForces 1200D White Lines
    HDU 6656 Kejin Player
    HDU 6651 Final Exam
  • 原文地址:https://www.cnblogs.com/zhaopp/p/11439261.html
Copyright © 2011-2022 走看看