feat:functions

This commit is contained in:
2026-03-01 21:26:49 +01:00
parent 7c53f67f14
commit 9606ca603e

View File

@@ -10,18 +10,51 @@ 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)
@@ -30,4 +63,22 @@ func main() {
_, 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))
}