feat:functions
This commit is contained in:
@@ -10,18 +10,51 @@ func plusPlus(a, b, c int) int {
|
|||||||
return a + b + c
|
return a + b + c
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// multiple return values
|
||||||
func vals() (int, int) {
|
func vals() (int, int) {
|
||||||
return 3, 7
|
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() {
|
func main() {
|
||||||
|
|
||||||
|
// functions
|
||||||
res := plus(1, 2)
|
res := plus(1, 2)
|
||||||
fmt.Println("1 + 2 =", res)
|
fmt.Println("1 + 2 =", res)
|
||||||
|
|
||||||
res = plusPlus(1, 2, 3)
|
res = plusPlus(1, 2, 3)
|
||||||
fmt.Println("1 + 2 + 3 =", res)
|
fmt.Println("1 + 2 + 3 =", res)
|
||||||
|
|
||||||
|
// multiple return values
|
||||||
a, b := vals()
|
a, b := vals()
|
||||||
|
|
||||||
fmt.Println(a)
|
fmt.Println(a)
|
||||||
@@ -30,4 +63,22 @@ func main() {
|
|||||||
_, c := vals()
|
_, c := vals()
|
||||||
fmt.Println(c)
|
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))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user