文章目录
1. 函数
在 Go 语言 中,使用 函数 前,必须先声明与定义函数。Go 语言的函数由 关键字 func、函数名、参数列表、返回值、函数体和 返回语句 组成。
2. 函数的声明
函数的声明,使用 func 关键字,后面依次接 函数名,参数列表,返回值列表,用 {} 包裹的代码逻辑体
func 函数名(形式参数列表)(返回值列表){
函数体
}
2.1 普通函数声明
2.1.1 有返回值的函数声明
//有返回值的函数
func test(str string) string{
return str+"无敌"
}
2.1.2 有多个返回值的函数声明
func test1(str string,str1 string) (string,string){
return str+"无敌",str1+"无敌"
}
2.1.3 返回值有变量名
func test2(str string) (str1 string) {
str1=str+"无敌"
return //不需要指定返回值,在上面已经指定了
}
2.2 可变参数的函数声明
可变参数分为几种:
多个类型一致的参数
多个类型不一致的参数
2.2.1 多个类型一致的参数
用 … 来表示可变参数,要放到参数最后一个
func test3(str ...string) string {
var a string
for _,d := range str{
a+=d
fmt.Println(d)
}
return a
}
2.2.2 多个类型不一致的参数
如果你希望传多个参数且这些参数的类型都不一样,可以指定类型为
…interface{} ,然后再遍历。
func test4(str ...interface{}) []interface{} {
var slice []interface{}
for _, d := range str {
switch d.(type) {
case int:
b := d
slice = append(slice, b)
case string:
c := d
slice = append(slice, c)
case []int:
d := d
slice = append(slice, d)
default:
e := d
f := reflect.TypeOf(e)
fmt.Println("sss", f)
slice = append(slice, e, f)
}
}
fmt.Println(slice)
return slice
}
贴上完整的代码
package main
import (
"fmt"
"reflect"
)
func main() {
sym := test("刘翔")
sym1, sym2 := test1("刘翔", "苏炳添")
sym4 := test("谷爱凌")
sym5 := test3("王一", "王二")
sym6 := test4("df", 1, []int{1, 2, 3}, test("姚明"), new(Anmail))
fmt.Println(sym) //输出:“刘翔无敌”
fmt.Println(sym1, sym2) //输出:“刘翔无敌 苏炳添无敌”
fmt.Println(sym4) //输出:“谷爱凌无敌”
fmt.Println(sym5) //输出:“王一王二”
fmt.Println(sym6) //输出:“[df 1 [1 2 3] 姚明无敌 0x10df458 *main.Anmail]”
}
type Anmail struct {
}
func test(str string) string {
return str + "无敌"
}
func test1(str string, str1 string) (string, string) {
return str + "无敌", str1 + "无敌"
}
func test2(str string) (str1 string) {
str1 = str + "无敌"
return
}
func test3(str ...string) string {
var a string
for _, d := range str {
a += d
}
return a
}
func test4(str ...interface{}) []interface{} {
var slice []interface{}
for _, d := range str {
switch d.(type) {
case int:
b := d
slice = append(slice, b)
case string:
c := d
slice = append(slice, c)
case []int:
d := d
slice = append(slice, d)
default:
e := d
f := reflect.TypeOf(e)
slice = append(slice, e, f)
}
}
return slice
}