Skip to content

Instantly share code, notes, and snippets.

@lilbond
Last active February 1, 2017 16:57
Show Gist options
  • Select an option

  • Save lilbond/0f19d8e495297e5650ca73d0e8760a0a to your computer and use it in GitHub Desktop.

Select an option

Save lilbond/0f19d8e495297e5650ca73d0e8760a0a to your computer and use it in GitHub Desktop.
A gist which touches upon various basic aspects of functions in Go. Explanation can be found here http://www.musingscafe.com/functions-in-golang/
package main
import (
"fmt"
)
func main() {
print("Hello, playground")
fmt.Println(sum(1, 2))
fmt.Println(mul(10, 5))
fmt.Println(sub(10, 5))
q, err := div(10, 5)
fmt.Println(q)
fmt.Println(err)
d, s := named(3)
fmt.Println(d)
fmt.Println(s)
a, err := average(1, 20)
fmt.Println(a)
fmt.Println(err)
avg, nError := averageWithNakedReturn(100, 20)
fmt.Println(avg)
fmt.Println(nError)
variableScope()
}
func print(message string) {
fmt.Println(message)
}
func sum(a int, b int) int {
return a + b
}
func mul(a, b int) int {
return a * b
}
func div(a, b int) (int , error) {
div := 0
if (b == 0) {
err := fmt.Errorf("Invalid Argument: Division by zero")
return div, err
}
return a / b, nil
}
func sub(a, b int) (diff int) {
diff = a - b
return diff
}
func named(value int) (doubled, squared int) {
fmt.Println(doubled)
fmt.Println(squared)
doubled = mul(value, 2)
squared = mul(value, value)
return
}
//A simple method, may not take care of corner cases
func average(start, end int) (avg int, err error) {
if start > end {
return avg, fmt.Errorf("Invalid arguments")
}
i := start
for i <= end {
avg = avg + i
i = i + 1
}
avg = avg / (end - start)
return
}
//A simple method, may not take care of corner cases
func averageWithNakedReturn(start, end int) (avg int, err error) {
if start > end {
err := fmt.Errorf("Invalid arguments")
return avg, err
}
i := start
for i <= end {
avg = avg + i
i = i + 1
}
avg = avg / (end - start)
return
}
func variableScope() {
message := "Hello"
//this one prints the outer scope message i.e. Hello
fmt.Println(message)
if 1 == 1 {
message := "Bye"
//this one prints the inner scope message i.e. Bye
fmt.Println(message)
}
//this one prints the outer scope message i.e. Hello
fmt.Println(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment