6.golang函数

函数是执行特定任务的代码块。函数接受输入,对输入执行一些计算,然后生成输出。

函数声明

在 go 中声明函数的语法是:

复制代码
func name(parameter) (result-list){
    //body
}

函数声明以func关键字开头,后跟name(函数名)。在括号中指定参数,后面为函数返回值result-list。参数和返回类型在函数中是可选的。因此,以下语法也是有效的函数声明。

复制代码
func name() {  
    //body
}

单返回值函数

复制代码
func plus(a, b int) (res int) {
	c := a + b
	return c
}

func main() {
	a, b := 90, 6
	sumAll := plus(a, b)
	fmt.Println("sum", sumAll)
}

上面程序,函数plus 接受两个 int 类型的值,并返回最终和。输出结果如下:sum 96

多返回值函数

复制代码
func plus(a, b int) (int, int) {
	c := a + b
	d := a - b
	return c, d
}

func main() {
	a, b := 90, 6
	sumAll, subAll := plus(a, b)
	fmt.Println("sum", sumAll)
	fmt.Println("sub", subAll)
}

输出结果如下:

复制代码
sum 96
sub 84

命名返回值

如果返回值被命名,相当由于在函数的第一行被声明为变量。

复制代码
func plus(a, b int) (res int) {
	res = a + b
	return
}

func main() {
	a, b := 90, 6
	sumAll := plus(a, b)
	fmt.Println("sum", sumAll)
}

输出结果如下:sum 96

参数可变函数

复制代码
func sum(nums ...int) (res int) {
	fmt.Println("len of nums is : ", len(nums))
	res = 0
	for _, v := range nums {
		res += v
	}
	return
}

func main() {
	fmt.Println(sum(1))
	fmt.Println(sum(1, 2))
	fmt.Println(sum(1, 2, 3))
}

输出结果如下:

复制代码
len of nums is :  1
1
len of nums is :  2
3
len of nums is :  3
6

匿名函数

复制代码
func main() {
	func(name string) {
		fmt.Println(name)
	}("初辰ge")
}
相关推荐
想用offer打牌5 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
lly2024066 小时前
Bootstrap 警告框
开发语言
2601_949146536 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧6 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
zmzb01037 小时前
C++课后习题训练记录Day98
开发语言·c++
爬山算法7 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
猫头虎7 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端