85 lines
1.1 KiB
Go
85 lines
1.1 KiB
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
func plus(a int, b int) int {
|
|
return a + b
|
|
}
|
|
|
|
func plusPlus(a, b, c int) int {
|
|
return a + b + c
|
|
}
|
|
|
|
// multiple return values
|
|
func vals() (int, int) {
|
|
return 3, 7
|
|
}
|
|
|
|
// variadic functions
|
|
func sum(nums ...int) {
|
|
fmt.Println(nums, " ")
|
|
total := 0
|
|
|
|
for _, num := range nums {
|
|
total += num
|
|
}
|
|
fmt.Println(total)
|
|
}
|
|
|
|
// Closures
|
|
func intSeq() func() int {
|
|
i := 0
|
|
return func() int {
|
|
i++
|
|
return i
|
|
}
|
|
}
|
|
|
|
// Recursion
|
|
func fact(n int) int {
|
|
print(n)
|
|
print("Recursion")
|
|
if n == 0 {
|
|
return 1
|
|
}
|
|
return n * fact(n-1)
|
|
}
|
|
|
|
func main() {
|
|
|
|
// functions
|
|
res := plus(1, 2)
|
|
fmt.Println("1 + 2 =", res)
|
|
|
|
res = plusPlus(1, 2, 3)
|
|
fmt.Println("1 + 2 + 3 =", res)
|
|
|
|
// multiple return values
|
|
a, b := vals()
|
|
|
|
fmt.Println(a)
|
|
fmt.Println(b)
|
|
|
|
_, c := vals()
|
|
fmt.Println(c)
|
|
|
|
// variadic
|
|
sum(1, 2, 3, 4, 5, 6)
|
|
sum(2, 10, 40)
|
|
sum([]int{5, 10, 10}...)
|
|
|
|
// Closures
|
|
nextInt := intSeq()
|
|
|
|
fmt.Println(nextInt())
|
|
fmt.Println(nextInt())
|
|
fmt.Println(nextInt())
|
|
|
|
newInts := intSeq()
|
|
fmt.Println(newInts())
|
|
|
|
// Recursion
|
|
// Classic recursion example
|
|
fmt.Println(fact(7))
|
|
}
|