Skip to content

Instantly share code, notes, and snippets.

@hsleonis
Created October 24, 2016 12:14
Show Gist options
  • Save hsleonis/46ac858e01322a571ad5a85bf0773ec8 to your computer and use it in GitHub Desktop.
Save hsleonis/46ac858e01322a571ad5a85bf0773ec8 to your computer and use it in GitHub Desktop.
Basic GoLang control flow
package main
import (
"fmt"
"strconv"
)
func main(){
var x int // Declare variable
fmt.Scanf("%d",&x) // Input
if x<5 { // If
fmt.Println("told ya")
} else if x>10 { // Else must be in the same line as ending '}'
fmt.Println("no way")
} else {
fmt.Println("he he")
}
if y := expensiveComputation(x); y>10 { // First assignment, then check
fmt.Println("no way at Y")
}
switch x%3 {
case 0:
fmt.Println("Good")
case 1:
fmt.Println("Better")
case 2:
fmt.Println("Best")
fallthrough // Falls through to next case
default:
fmt.Println("Never say never")
}
for i:=0; i<x; i++ { // Simple For Loop [ Only loop in GoLang ]
fmt.Print("Iteration ", i, ", ") // Multivalue print
}
for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} {
// for each pair in the map, print key and value
fmt.Printf("key=%s, value=%d\n", key, value)
}
fmt.Println( do(21) )
fmt.Println( do("bitrab") )
fmt.Println( do(3.142) )
}
func expensiveComputation(x int)(y int){
return x+2
}
func do(v interface{}) string {
switch u := v.(type) {
case int:
return strconv.Itoa(u*2) // u has type int
case string:
mid := len(u) / 2 // split - u has type string
return u[mid:] + u[:mid] // join
}
return "unknown"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment