go函数变长参数

变长参数定义

Go函数的变长参数类似于PHP5.6之后的方式

func myFunc(a,b...int){}

变长参数要点:

  • 变长参数必须为最后一个
  • 可以通过for循环获取参数
  • 类型不同的变长参数可以通过结构空接口来实现

相同类型变长参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

func main() {
sum("获取变长参数",1,2,3)
}

func sum(desc string,numbers ...int){
fmt.Println(desc)
for _,number := range numbers{
fmt.Println(number)
}
}
//获取变长参数
//1
//2
//3

不通类型变长参数

结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}

func main() {
var Book1 Books

Book1.title = "Go 语言"
Book1.author = "www.xxx.com"
Book1.subject = "Go 语言教程"
Book1.book_id = 6495407

printBook("结构体作为变长参数",Book1)
}


func printBook(desc string,book Books){
fmt.Println(desc)
fmt.Printf( "Book title : %s\n", book.title);
fmt.Printf( "Book author : %s\n", book.author);
fmt.Printf( "Book subject : %s\n", book.subject);
fmt.Printf( "Book book_id : %d\n", book.book_id);
}

//结构体作为变长参数
//Book title : Go 语言
//Book author : www.xxx.com
//Book subject : Go 语言教程
//Book book_id : 6495407

空接口

1
2
3
4
5
6
7
8
9
func typeCheck(values ...interface{}){
for _,value := range values{
switch v:= value.(type) {
case int:
case string:
default:
}
}
}