赞
踩
在 Golang 中,函数就像是代码的超级组合体,可以将一段代码封装成一个独立的单元,以便重复使用。
func funcName(parameter1 type1, parameter2 type2) returnType {
// 函数体
}
Example 1: 电话问候方法调用
func sayGreeting (n string) {
fmt.Printf("Good morning %v \n", n)
}
func sayBye(n string) {
fmt.Printf("Goodbye %v \n", n)
}
func main() {
ayGreeting("小叮当")
sayGreeting("静香")
sayBye("小叮当")
}
Output:
Good morning 小叮当
Good morning 静香
Goodbye 小叮当
Eample 2:多人之间问候
func sayGreeting (n string) { fmt.Printf("Good morning %v \n", n) } func sayBye(n string) { fmt.Printf("Goodbye %v \n", n) } func cycleNames(n []string, f func(string)){ for _, v := range n { f(v) } } func main() { cycleNames([]string{"大雄", "小夫", "胖虎"}, sayGreeting) cycleNames([]string{"大雄", "小夫", "胖虎"}, sayBye) }
Output:
Good morning 大雄
Good morning 小夫
Good morning 胖虎
Goodbye 大雄
Goodbye 小夫
Goodbye 胖虎
Eample3:求圆面积
为了引用math.Pi方法,我们要import进入math的package
import (
"fmt"
"math"
)
func circleArea(r float64) float64 {
return math.Pi * r * r
}
func main() {
a1 := circleArea(10.5)
a2 := circleArea(15)
fmt.Println(a1, a2)
fmt.Printf("circle 1 is %0.3f and circle 2 is %0.3f", a1, a2)
}
Output:
346.36059005827474 706.8583470577034
circle 1 is 346.361 and circle 2 is 706.858
函数是 Golang 中重要的编程概念,可以帮助你将代码组织成更小的单元,提高代码的复用性和可维护性。当然,函数在你成为golang编写代码后也必是生产工作中不可或缺的一部分。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。