Skip to content

Instantly share code, notes, and snippets.

@shockalotti
shockalotti / Go Golang - name function return
Created May 27, 2014 07:43
Go Golang - name function return
package main
import "fmt"
func f1() (r int) {
r = 1
return
}
func main() {
fmt.Println(f1())
@shockalotti
shockalotti / Go Golang - return multiple values from a function
Created May 27, 2014 07:49
Go Golang - return multiple values from a function
package main
import "fmt"
func f() (int,int,int) {
return 5,6,7
}
func main() {
x,y,z:=f()
@shockalotti
shockalotti / Go Golang - variadic function (with unknown number of arguments)
Created May 27, 2014 08:02
Go Golang - variadic function (with unknown number of arguments)
package main
import "fmt"
func add(args ...int) int {
total :=0
for _, v := range args {
total += v
}
return total
@shockalotti
shockalotti / Go Golang - pass a variable slice of ints to function
Created May 27, 2014 08:12
Go Golang - pass a variable slice of ints to function
package main
import "fmt"
func add(args ...int) int {
total :=0
for _, v := range args {
total += v
}
return total
@shockalotti
shockalotti / Go Golang - basic Closure example
Created May 27, 2014 08:16
Go Golang - basic Closure example
package main
import "fmt"
func main() {
add := func(x,y int) int {
return x + y
}
fmt.Println(add(1,1))
}
@shockalotti
shockalotti / Go Golang - Closures have access to other local variables
Created May 27, 2014 08:21
Go Golang - Closures have access to other local variables
package main
import "fmt"
func main() {
x := 0
increment := func() int {
x++
return x
}
@shockalotti
shockalotti / Go Golang - closure example, nextEven function
Created May 28, 2014 01:22
Go Golang - closure example, nextEven function
package main
import "fmt"
func makeEvenGenerator() func() uint {
i := uint(0)
return func() (ret uint) {
ret = i
i += 2
return
@shockalotti
shockalotti / Go Golang - recursion function, calculate factorial
Created May 28, 2014 01:33
Go Golang - recursion function, calculate factorial
package main
import "fmt"
func factorial(x uint) uint {
if x == 0 {
return 1
}
return x * factorial(x-1)
@shockalotti
shockalotti / Go Golang - basic Defer function
Created May 28, 2014 01:38
Go Golang - basic Defer function
package main
import "fmt"
func first() {
fmt.Println("1st")
}
func second() {
fmt.Println("2nd")
}
@shockalotti
shockalotti / Go Golang - Defer, Panic function example
Created May 28, 2014 01:45
Go Golang - Defer, Panic function example
package main
import "fmt"
func main() {
defer func() {
str := recover()
fmt.Println(str)
}()
panic("PANIC")