Skip to main content

函数 Functions

func sub(x int, y int) int {
return x - y
}

func concat(s1 string, s2 string) string {
return s1 + s2
}

Multiple parameters

When multiple arguments are of the same type, the type only needs to be declared after the last one, assuming they are in order.

func add(x, y int) int {
return x + y
}

func createUser(firstName, lastName string, age int) {
fmt.Printf("My name is %s %s, I'm %d years old\n", firstName, lastName, age)
var returnOfSprintf string = fmt.Sprintf("My name is %s %s, I'm %d years old\n", firstName, lastName, age)
fmt.Println(returnOfSprintf)
}

Multiple returnValue

func vals() (int, int) {
return 3, 7
}

Name parameters/returnValues

有利于更好理解函数参数和输出的意义。

func vals(firstParameter int, secondParameter int) (firstReturn int, secondReturn int) {
return 3, 7
}

Ignore returnValue

firstReturn, _ := vals(1, 2)

可变参数 Variadic

func sum(nums ...float64) float64 {
// nums is just a slice
total = 0.0
for i := 0; i < len(nums); i++ {
total += nums[i]
}
return total
}

The familiar fmt.Println() and fmt.Sprintf() are variadic! fmt.Println() prints each element with space delimiters and a newline at the end.

func Println(a ...interface{}) (n int, err error)

Spread operator

The spread operator allows us to pass a slice into a variadic funciton. The spread oeprator consists of three dots following the slice in the function call.

func printStrings(strings ...string) {
for i := 0; i < len(strings); i++ {
fmt.Println(strings[i])
}
}

func main() {
names := []string{"bob", "sue", "alice"}
printStrings(names...)
}