go语言 函数拥有不定参数,闭包函数

go语言函数定义:

返回单个值:

func Add(a int, b int) int {
      return a+b
}

返回多个值:

func Add(a int, b int) (ret int, err error){
    return a+b, nil//支持多重返回值
}

拥有不定参数:

func 函数名(args ...interface{}){

}

interface{}可以指定不定参数类型为任意类型,

// varg1
package main

import (
	"fmt"
)

func MyPrintf(args ...interface{}) {
	for _, arg := range args {
		switch arg.(type) {
		case int:
			fmt.Println(arg, "is an int value")
		case string:
			fmt.Println(arg, "is a string value.")
		case int64:
			fmt.Println(arg, "is an int64 value.")
		default:
			fmt.Println(arg, "is an unknown type.")
		}
	}
}

func main() {
	var v1 int = 1
	var v2 int64 = 234
	var v3 string = "hello"
	var v4 float32 = 1.234
	MyPrintf(v1, v2, v3, v4)
}

该程序输出结果为:

1 is an int value.

234 is an int64 value.

hello is a string value.

1.234 is an unknown type.

没写返回值,是因为没有返回值吗?

闭包函数:

 // closure
package main

import (
	"fmt"
)

func main() {
	var j int = 5
        //从此开始 begin
	a := func() func() {
		var i int = 10
		return func() {
			fmt.Printf("i, j: %d, %d\n", i, j)
		}
	}()
        //到这里时一个闭包函数,返回一个func(),返回值赋给a.
        //调用这个闭包函数
	a()
	j *= 2
	a()
}

 

你可能感兴趣的:(golang)