Switch
The provided Go code demonstrates the usage of the switch
statement in various scenarios.
Let's break down the code step by step:
Explanation:
Basic Switch with Integer (
i
):The code initializes an integer
i
with the value 2.The
switch
statement checks the value ofi
and prints the corresponding word for the number.
Switch with
time.Weekday
:The code uses the
time.Now().Weekday()
function to get the current day of the week.The
switch
statement checks if it's Saturday or Sunday and prints a message accordingly.
Switch without Expression (
t.Hour()
):The code uses the current time (
time.Now()
) and checks the hour usingt.Hour()
.The
switch
statement doesn't have a specific expression but evaluates conditions based on the hour.
Switch with Type Assertion (
whatAmI
function):The code defines a function
whatAmI
that takes an empty interface (interface{}
), allowing it to accept values of any type.Inside the function, a
switch
statement uses type assertion (i.(type)
) to determine the type of the input and prints a message accordingly.
Example outputs:
I'm a bool
fortrue
I'm an int
for1
Don't know type string
for"hey"
This code showcases the flexibility and power of the switch
statement in Go, allowing developers to handle different types of conditions and expressions efficiently.
Output
Last updated
Was this helpful?