Golang学习笔记_02——函数
函数
Go语言中的函数是一种基本的编程结构,用于封装一段代码,以便在需要时多次调用。函数可以接收参数并返回结果,是实现代码复用和模块化编程的重要手段。
1. 定义
在Go语言中,函数通过func
关键字定义。一个基本的函数定义包括函数名、参数列表、返回类型(如果有的话)、以及函数体。
当连续两个或多个函数的已命名形参类型相同时,除最后一个类型以外,其它都可以省略。
package function_demo
func add(a int, b int) int {
return a + b
}
add
函数接收两个int
类型的参数,并返回一个int
类型的结果。
对刚刚定义的函数进行测试
package function_demo
import (
"fmt"
"testing"
)
func TestFunctionDemo(t *testing.T) {
fmt.Println("sum = ", add(1, 2))
}
测试结果
=== RUN TestFunctionDemo
sum = 3
--- PASS: TestFunctionDemo (0.00s)
PASS
2. 返回值
Go语言中的函数可以返回多个值。这在处理错误或其他需要返回多个结果的情况下非常有用。
func AddAndSubtract(a int, b int) (int, int) {
sum := a + b
diff := a - b
return sum, diff
}
测试方法
func TestAddAndSubtract(t *testing.T) {
sum, diff := AddAndSubtract(100, 99)
fmt.Println("sum = ", sum, "\n", "diff = ", diff)
}
输出结果
=== RUN TestFunctionDemo2
sum = 199
diff = 1
--- PASS: TestFunctionDemo2 (0.00s)
PASS
3. 命名返回值
Go语言支持命名返回值,这可以让代码更加清晰和简洁。
命名返回值在函数定义时指定名称,并在函数体中直接使用这些名称,最后通过裸返回(即直接写return
)来返回这些值。
func addAndSubtractNamed(a int, b int) (sum int, diff int) {
sum = a + b
diff = a - b
return sum, diff
}
测试方法
func Test_addAndSubtractNamed(t *testing.T) {
sum, diff := AddAndSubtract(1000, 99)
fmt.Println("sum = ", sum, "\n", "diff = ", diff)
}
输出结果
=== RUN Test_addAndSubtractNamed
sum = 1099
diff = 901
--- PASS: Test_addAndSubtractNamed (0.00s)
PASS
4. 可变参数
Go语言中的函数也支持可变参数(即接收不定数量的参数)。
通过将一个参数类型设置为...T
(其中T
是参数类型),可以定义一个可变参数列表。
func sumAll(nums ...int) int {
sum := 0
for _, num := range nums {
sum += num
}
return sum
}
测试方法
func Test_sumAll(t *testing.T) {
fmt.Println("sum all = ", sumAll(1, 2, 3, 100, -90))
}
输出结果
=== RUN Test_sumAll
sum all = 16
--- PASS: Test_sumAll (0.00s)
PASS
源码
// function_demo.go
package function_demo
func add(a int, b int) int {
return a + b
}
func AddAndSubtract(a int, b int) (int, int) {
sum := a + b
diff := a - b
return sum, diff
}
func addAndSubtractNamed(a int, b int) (sum int, diff int) {
sum = a + b
diff = a - b
return sum, diff
}
func sumAll(nums ...int) int {
sum := 0
for _, num := range nums {
sum += num
}
return sum
}
// function_demo_test.go
package function_demo
import (
"fmt"
"testing"
)
func TestFunctionDemo(t *testing.T) {
fmt.Println("sum = ", add(1, 2))
}
func TestAddAndSubtract(t *testing.T) {
sum, diff := AddAndSubtract(100, 99)
fmt.Println("sum = ", sum, "\n", "diff = ", diff)
}
func Test_addAndSubtractNamed(t *testing.T) {
sum, diff := AddAndSubtract(1000, 99)
fmt.Println("sum = ", sum, "\n", "diff = ", diff)
}
func Test_sumAll(t *testing.T) {
fmt.Println("sum all = ", sumAll(1, 2, 3, 100, -90))
}
原文地址:https://blog.csdn.net/LuckyLay/article/details/144371981
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!