<aside> 💡 函数的定义,匿名函数,闭包,延迟函数的使用
</aside>
func functionname(parametername type) returntype {
// 函数体(具体实现的功能)
}
func calculateBill(price int, no int) int {
var totalPrice = price * no // 商品总价 = 商品单价 * 数量
return totalPrice // 返回总价
}
package main
import (
"fmt"
)
func rectProps(length, width float64)(float64, float64) {
var area = length * width
var perimeter = (length + width) * 2
return area, perimeter
}
func main() {
area, perimeter := rectProps(10.8, 5.6)
fmt.Printf("Area %f Perimeter %f", area, perimeter)
}
func rectProps(length, width float64)(area, perimeter float64) {
area = length * width
perimeter = (length + width) * 2
return // 不需要明确指定返回值,默认返回 area, perimeter 的值
}
请注意, 函数中的 return 语句没有显式返回任何值。由于 area 和 perimeter 在函数声明中指定为返回值, 因此当遇到 return 语句时, 它们将自动从函数返回。
_ 在 Go 中被用作空白符,可以用作表示任何类型的任何值。
package main
import (
"fmt"
)
func rectProps(length, width float64) (float64, float64) {
var area = length * width
var perimeter = (length + width) * 2
return area, perimeter
}
func main() {
area, _ := rectProps(10.8, 5.6) // 返回值周长被丢弃
fmt.Printf("Area %f ", area)
}