1. 函数的值传递和引用传递、返回值
package main
import (
"fmt"
"math"
)
func main() {
// 值传递,只需声明函数变量
getSquareRoot := func(x float64) float64 {
return math.Sqrt(x)
}
fmt.Println(getSquareRoot(9))
// 引用传递,形参中传入的是变量地址
var x = 3
x1 := add(&x)
fmt.Println("x =", x)
fmt.Println("x1 =", x1)
_, b := swap("Mahesh", "Humar")
fmt.Println(b)
x, y := SumAndProduct(10, 12)
fmt.Println(x, y)
}
// 一个函数可以有一个返回值
func add(a *int) int {
*a += 1
return *a
}
// 一个函数可以没有返回值
func SumAndProduct(A, B int) (add int, Multiplied int) {
add = A + B
Multiplied = A * B
return
}
// 一个函数可以有多个返回值
func swap(x, y string) (string, string) {
return y, x
}
2. 延迟函数(defer)
package main
import (
"fmt"
)
// 延迟语句发生在被调函数返回之前,多个延迟语句将会逆序执行
// 结构体
type person struct {
firstName string
lastName string
}
func main() {
// 延迟函数,求数组中的最大值
nums := []int{78, 105, 2, 98}
largest(nums)
// 延迟参数
printALL()
// 延迟方法
p := person{
"John",
"Smith",
}
defer p.fullName()
fmt.Println("welcome")
}
// 延迟函数
func finished() {
fmt.Println("Finished")
}
func largest(nums []int) {
defer finished()
max := nums[0]
for _, value := range nums {
if value > max {
max = value
}
}
fmt.Println("largest number in", nums, "is", max)
}
// 延迟参数
func printA(a int) {
fmt.Println("value of a in deferred function", a)
}
func printALL() {
a := 5
defer printA(a)
a = 10
fmt.Println("value of a in deferred function", a)
}
// 延迟方法
func (p person) fullName() {
fmt.Printf("%s %s", p.firstName, p.lastName)
}
运行结果:
largest number in [78 105 2 98] is 105
Finished
value of a in deferred function 10
value of a in deferred function 5
welcome
John Smith
3. 函数运用
package main
import "fmt"
// 定义一个接口,包含两个方法
type shape interface {
area() int
getType() string
}
// 声明一个矩形结构体
type rectangle struct {
length int
breath int
}
// 声明一个正方形结构体
type square struct {
side int
}
// 用户自定义函数类型
type area func(int, int) int
func main() {
// 函数的常规使用
res := sum(2, 3)
fmt.Println(res)
// 函数类型:表示所有包含相同参数和返回类型的函数集合
var shapes []shape
s := &square{side: 2}
r := &rectangle{2, 3}
shapes = append(shapes, s)
shapes = append(shapes, r)
for _, shape := range shapes {
fmt.Printf("Type:%s, Area:%d\n", shape.getType(), shape.area())
}
// 用户自定义函数类型
areaF := getAreaFunc()
print(3, 4, areaF)
}
func sum(a, b int) int {
return a + b
}
func (r *rectangle) area() int {
return r.breath * r.length
}
func (r *rectangle) getType() string {
return "rectangle"
}
func (r *square) area() int {
return r.side * r.side
}
func (r *square) getType() string {
return "square"
}
// 高阶函数:将一个函数fun2作为函数fun1的一个参数
// print 函数将 func(int, int) int 作为一个参数
func print(x, y int, a area) {
fmt.Printf("Arrea is:%d\n", a(x, y))
}
// 闭包:一个外层函数中,有内层函数,该内层函数中,会操作外层函数的局部变量(外层函数中的参数,或者外层函数中直接定义的变量),
// 并且该外层函数的返回值就是这个内层函数。
// getAreafunc() 返回 int
func getAreaFunc() area {
return func(x, y int) int {
return x * y
}
}
运行结果:
5
Type:square, Area:4
Type:rectangle, Area:6
Arrea is:12