初识GoLang函数

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值