How to use switch statement in Go

4 Answers

0 votes
package main
 
import "fmt"
 
func main() {
	n := 3
    switch n {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    case 4:
        fmt.Println("four")
    }
}
 
 
 
/*
run:
 
three

*/

 



answered Feb 21, 2020 by avibootz
0 votes
package main
 
import (
    "fmt"
    "time"
)
 
func main() {
	t := time.Now()
	
    switch {
    case t.Hour() > 13:
        fmt.Println("> 13")
    default:
        fmt.Println("< 13")
    }
}
 
 
 
/*
run:
 
> 13

*/

 



answered Feb 21, 2020 by avibootz
0 votes
package main
 
import (
    "fmt"
)
 
func main() {
	f := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("bool")
        case int:
            fmt.Println("int")
		case string:
            fmt.Println("string")
        default:
            fmt.Printf("type is = ", t)
        }
    }
    f(12)
    f(true)
    f("golang")
    f(false)
	f(3.14)
}
 
 
 
/*
run:
 
int
bool
string
bool
type is = %!(EXTRA float64=3.14)

*/

 



answered Feb 21, 2020 by avibootz
0 votes
package main

import (
    "fmt"
)

func main() {
	switch os := "go"; os {
	case "python":
		fmt.Println("Python")
	case "go":
		fmt.Println("Go")
	default:
		fmt.Printf("default")
	}
}



/*
run:

Go

*/

 



answered Mar 6, 2020 by avibootz
...