网站首页 返回列表 像“草根”一样,紧贴着地面,低调的存在,冬去春来,枯荣无恙。
golang 基础(F)函数的参数
2020-06-10 02:48:54 admin 944
square-gopher.png
函数
函数是由函数名,参数,返回值和函数体所组成。
__
func add(a, b int) int {}
定义函数并且复习一下之前的 switch 语句
__
func eval(a, b int,op string) int {
switch op {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
return a / b
default:
panic("unsupported operation: " + op)
}
}
在 go 语言中 { 需要 bar() 在同一行不言就会报错
__
func bar() //报错
{
}
__
.\funtions.go:26:6: missing function body
.\funtions.go:27:1: syntax error: unexpected semicolon or newline before {
函数中的参数
定义函数可以没有任何参数就像 main 函数
__
func main(){
}
定义函数的参数时和其他语言没有什么不同,指定参数名称和参数类型
__
func sayMessage(msg string){
// body
}
如果参数类型一致我们可以省略 greeting 后面指定类型
__
func sayGreeting(greeting, name string){
fmt.Println(greeting, name)
}
我们可以尝试在 sayGreeting 内部修改 name 这个变量,因为函数作用域这些修改name 不会影响到函数外面的 name 值,这是大家的尝试。
__
func sayGreeting(greeting, name string){
fmt.Println(greeting, name)
name ="matthew"
fmt.Println(name)
}
__
greeting := "hello"
name := "zidea"
sayGreeting(greeting,name)
fmt.Println(name)
从结果来看
__
hello zidea
matthew
zidea
外面的 name 值依旧是 zidea 没有发生变化
我们可以将传递变量引用修改为将变量的地址作为参数传给函数
__
func sayGreeting(greeting, name *string){
fmt.Println(*greeting, *name)
*name ="matthew"
fmt.Println(*name)
}
__
hello zidea
matthew
matthew
__
func main(){
fmt.Println(eval(3,4, "*"))
greeting := "hello"
name := "zidea"
fmt.Println(greeting, name)
}
我们也可以通过( … )来实现函数动态地传入多个参数,这和 es6 语法很相似。
__
func sum(values ...int){
fmt.Println(values)
result := 0
for _, v := range values{
result += v
}
fmt.Println("The sum is ", result)
}
Golang1.png
转载文章,原文链接:
golang 基础(F)函数的参数
上一篇:Go 的并发模式(中)(更新中)
0 条评论 0 人参与