more examples
This commit is contained in:
parent
dbc1292105
commit
bf872f0919
22
gobyexample/closures.go
Normal file
22
gobyexample/closures.go
Normal file
@ -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())
|
||||||
|
}
|
19
gobyexample/functions.go
Normal file
19
gobyexample/functions.go
Normal file
@ -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)
|
||||||
|
}
|
16
gobyexample/multiple-return-values.go
Normal file
16
gobyexample/multiple-return-values.go
Normal file
@ -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)
|
||||||
|
}
|
25
gobyexample/recursion.go
Normal file
25
gobyexample/recursion.go
Normal file
@ -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))
|
||||||
|
}
|
20
gobyexample/variadic-functions.go
Normal file
20
gobyexample/variadic-functions.go
Normal file
@ -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...)
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user