一: 函数
1) 自定义函数
函数声明的格式
func 函数名 ( [参数列表] ) [返回值列表] {
函数体
}
方法名首字母大写是 public, 方法名首字母小写 private 私有方法
2) 函数类型
- package main
- import (
- "fmt"
- )
- //1 无参无返回值
- func test(){
- fmt.Println("三无产品")
- }
- //2 有参无返回值
- func test1(v1 int,v2 int){
- fmt.Println(v1,v2)
- }
- //3 有不定参数无返回值
- func test2(args ...int){
- for _,n :=range args{
- fmt.Println(n)
- }
- }
- // 调用以上函数
- func main(){
- test()
- test1(1,2)
- test2(1,2,3,4)
- }
- package main
- import "fmt"
- // 无参有返回值
- func test4(a int ,str string){
- a = 666
- str= "我是沙雕"
- return
- }
- func test5() (int,string){
- return 250,"字符串"
- }
- func main(){
- a,str := test4() //test4 没有返回值, 运行会报错
- fmt.Println(a,str)
- _,s :=test5()
- fmt.Println(s)
- }
- package main
- import (
- "fmt"
- )
- // 有参有返回值
- // 求两个数的最大值和最小值
- func test1(num1 int,num2 int) (min int,max int){
- if num1>num2{
- min=num2
- max=num1
- }else {
- max=num2
- min=num1
- }
- return
- }
- func main(){
- min,max := test1(33,22)
- fmt.Println(min,max)
- }
求 1~100 的和代码实现两种方法
- package main
- import "fmt"
- // 循环实现 1 到 100 累加
- func test01() int {
- sum :=0
- for i :=1;i<=100;i++{
- sum +=i
- }
- return sum
- }
- // 递归实现 1 到 100 的累加
- func test02(num int)int{
- if num==1{
- return 1
- }
- return num +test02(num-1)
- }
- func main() {
- fmt.Println(test01())
- fmt.Println(test02(100))
- }
未完待续 .......
来源: http://www.bubuko.com/infodetail-3043494.html