前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go函数知识

Go函数知识

作者头像
苦咖啡
发布2018-04-28 11:26:21
5550
发布2018-04-28 11:26:21
举报
文章被收录于专栏:我的博客我的博客我的博客
1.函数格式
func funcName(input1 type1, input2 type2) (output1 type1, output2 type2) {
//这里是处理逻辑代码
//返回多个值
return value1, value2
}
示例:
func max(a, b int) int {
if a > b {
return a
}
return b
}

2.多个返回值
func add(a, b int) (int,int) {
return a,a+b
}

3.参数个数不确定

func add(t ... int) (r int) {
for _, n := range t {
r+=n
fmt.Printf("And the number is: %d\n", n)
}
return
}

4.值传递和指针传递
值传递
func add(a int) int {
a=a+1
return a
}
func main() {
a:=1
b:=add(a)
fmt.Println(a)
fmt.Println(b)
}

指针传递
func add(a *int) int {
*a=*a+1
return *a
}
func main() {
a:=1
b:=add(&a)
fmt.Println(a)
fmt.Println(b)
}

5.defer
如果有很多调用defer,那么defer是采用后进先出模式可以在函数中添加多个defer语句。当函数执行到最后时,这些defer语句会按照逆序执行,最后该函数返回

6.函数作为类型
type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
备注:定义为typeName类型的函数当做值来传递

7.panic和recover

func badCall() {
panic("bad end")
}

func test() {
defer func() {
if e := recover(); e != nil {
fmt.Printf("Panicing %s\r\n", e)
}
}()
badCall()
fmt.Printf("After bad call\r\n") // <-- wordt niet bereikt
}

func main() {
fmt.Printf("Calling test\r\n")
test()
fmt.Printf("Test completed\r\n")
}

8.main和init
点操作:你可以省略前缀的包名,也就是前面你调用的fmt.Println("hello world")可以省略的写成Println("hello world")
别名操作:别名操作的话调用包函数时前缀变成了我们的前缀
_空操作:别名操作的话调用包函数时前缀变成了我们的前缀
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年8月2日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档