go语言:可变参数

1、go 语言通过占位符... 实现可变参数。
2、对于未知类型通过 interface{}实现。interface{}可以理解为c/c++中void类型

具体如下:

package main

import (
	"fmt"
)
/// 此时需指定类型int
func TestFuncInt(args ... int) {
	fmt.Println(args)
}
/// 此时需指定类型string
func TestFuncStr(args ...string) {
	fmt.Println(args)
}


/// interface{}可以理解为c/c++中void类型
func TestFuncAll(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() {
	TestFuncInt(2, 3, 5)
	TestFuncStr("str", "is", "test")

	/// 支持slice方式
	data := []int{1,2,3}
	TestFuncInt(data...)

	TestFuncAll(2, "str", 4)
}

输出

[2 3 5]
[str is test]
[1 2 3]
2 is an int value.
str is a string value
4 is an int value.

资料:
https://zhuanlan.zhihu.com/p/411663311
https://www.jianshu.com/p/01431eafbed2

posted @ 2023-08-21 15:55  小海哥哥de  阅读(20)  评论(0编辑  收藏  举报