diff --git a/gobyexample/closures.go b/gobyexample/closures.go new file mode 100644 index 0000000..f215391 --- /dev/null +++ b/gobyexample/closures.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func intSeq() func() int { + i := 0 + return func() int { + i++ + return i + } +} + +func main() { + nextInt := intSeq() + + fmt.Println(nextInt()) + fmt.Println(nextInt()) + fmt.Println(nextInt()) + + newInts := intSeq() + fmt.Println(newInts()) +} diff --git a/gobyexample/functions.go b/gobyexample/functions.go new file mode 100644 index 0000000..b2081ee --- /dev/null +++ b/gobyexample/functions.go @@ -0,0 +1,19 @@ +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 +} + +func main() { + res := plus(1, 2) + fmt.Println("1+2 =", res) + + res = plusPlus(1, 2, 3) + fmt.Println("1+2+3 =", res) +} diff --git a/gobyexample/multiple-return-values.go b/gobyexample/multiple-return-values.go new file mode 100644 index 0000000..da8515a --- /dev/null +++ b/gobyexample/multiple-return-values.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func vals() (int, int) { + return 3,7 +} + +func main() { + a,b := vals() + fmt.Println(a) + fmt.Println(b) + + _, c := vals() + fmt.Println(c) +} diff --git a/gobyexample/recursion.go b/gobyexample/recursion.go new file mode 100644 index 0000000..cdac8a1 --- /dev/null +++ b/gobyexample/recursion.go @@ -0,0 +1,25 @@ +package main + +import "fmt" + +func fact(n int) int { + if n==0 { + return 1 + } + return n * fact(n-1) +} + +func main() { + fmt.Println(fact(7)) + + var fib func(n int) int + + fib = func(n int) int { + if n<2 { + return n + } + return fib(n-1) + fib(n-2) + } + + fmt.Println(fib(7)) +} diff --git a/gobyexample/variadic-functions.go b/gobyexample/variadic-functions.go new file mode 100644 index 0000000..e003341 --- /dev/null +++ b/gobyexample/variadic-functions.go @@ -0,0 +1,20 @@ +package main + +import "fmt" + +func sum(nums ...int) { + fmt.Print(nums, " ") + total := 0 + for _, num := range nums { + total += num + } + fmt.Println(total) +} + +func main() { + sum(1,2) + sum(1,2,3) + + nums := []int{1, 2, 3, 4} + sum(nums...) +}