Conditions / Loops

if/else, for and struct

If condition

package main

import (
	"fmt"
//	"math"
)


func main() {
	
	// conditions: if/else/if-else, no ternary operator (a?b:c)
	
	if 3%2 == 0{
		fmt.Println("even")
	}
	else{
	fmt.Println("odd")
	}
	
	}
  • No parenthesis required in conditions

  • There is no ternary operator in Go

For loop

package main

import (
	"fmt"
//	"math"
)


func main() {
	
	// for loop: only looping construct
	i := 1
	for i < 3{
	fmt.Println(i)
	i ++
	}

	// with one condition, with initials, limit and increment
	for i:=0; i< 10; i++{
	fmt.Println(i)
	}
	
	// without condition: like infinite	
	for {
	fmt.Println("hello")
	break
	}
	
	}

switch

package main

import ( 
    "fmt" 
    "time" 
    )

func main() {
// basic switch statement
i := 3
fmt.Println("the value", i, "is")
switch i{

case 1:
    fmt.Println("one")
case 2:
    fmt.Println("two")
case 3:
    fmt.Println("three")
}

// multiple expressions in case 
switch time.Now().Weekday(){
case time.Saturday, time.Sunday:
    fmt.Println("its weekend")
default:
    fmt.Println("its weekend")
}

// swtich as if/else behavior
t := time.Now() // some condition
switch {
case t.Hour() < 12:
    fmt.Println("its afternoon")
default:
    fmt.Printf("not noon")

}
}

Last updated

Was this helpful?