Hi, I'm back
This is the third part of Golang tutorial series, if you haven't checked out the first & second parts, do check it out here.
Control Constructs in Go
Go provides following statements for controlling the program flow:
If statement
Syntax:
// Regular if
if condition {
...
}
// Initialised if
if initialisation; condition {
...
}
// if-else
if condition {
...
} else {
...
}
if condition1 {
...
} else if condition2 {
...
} else {
...
}
Points to remember:
- Go provides two syntaxes for
ifstatements, one with initialisation & one without initialisation. - Braces are mandatory, even for one line.
- The
{(opening brace) after theifandelsemust be on the same line. - The
else ifandelsemust be on same line as}(closing brace). - Can use parentheses for composite expressions with &&, ||, !
- The
;afterinitialisationis required. - Use local assignments (
:=) forinitialisationin initialised if statements. - Scope of initialisation variable is known only within
ifstatement. - Can also invoke functions to initialise variable in the initialised if statements.
Example:
package main
import ("fmt"; "runtime")
func main() {
if platform := runtime.GOOS; platform == "linux" { // fetch os info
fmt.Println("linux platform")
} else if platform == "darwin" {
fmt.Println("darwin platform")
} else {
fmt.Println("windows platform")
}
}
Switch Statement
Syntax:
// Regular switch
switch variable {
case val1:
...
case val2:
...
default:
...
}
// Initialised switch
switch initialisation; variable {
case val1:
...
case val2:
...
default:
...
}
// Tag-less switch
switch {
case boolexpr1:
...
case boolexp2:
...
default:
...
}
Points to remember:
- Go provides three syntaxes for
switchstatement. - The
{(opening brace) must be on the same line as theswitch -
variablecan be any type. -
val1,val2must be of the same type. - More than one value may appear in a case.
- Breaks from each case are implicit.
- Use keyword
fallthroughto combinecaseconditions. - Braces (
{and}) are allowed in case for multiple statements. - Use keyword
defaultto handle conditions that match nocase - Keyword
defaultmay be placed anywhere in switch. - In tag-less switch statements,
casestatements must evaluate to boolean expressions.
Example:
package main
import ("fmt"; "runtime", "os")
func main() {
switch platform := runtime.GOOS; platform {
case "linux", "darwin", "windows": // multiple cases
fmt.Println("Known OS")
default:
fmt.Println("Unknown OS")
}
arg := os.Args[1] // fetch command line argument
num, _ := strconv.ParseFloat(arg, 64) // string to float64
var val float64
switch {
case num < 0:
num = -num
fallthrough // fallthrough to second case
case num > 0:
val = math.Sqrt(num)
case num == 0:
val = 0;
}
fmt.Println(val)
}
For statement
Syntax:
// Counter controlled loop
for initialisation; condition; update {
...
}
// Condition controlled loop
for condition {
...
}
// Range controlled loop
for index, value := range collection {
...
}
for index := range collection {
...
}
Points to remember:
- Go provides three syntaxes for
forstatement. - No while or do while statements.
- Braces are mandatory, even for one line.
- Opening brace
{must be on the same line asfor - Surrounding parenthesis after
forare not allowed. - May assign more than one counter in initialise with commas
- Omitting
conditionin a condition controlled loop results in an infinite loop. - In range controlled loops,
collectionis a sequence of items (string, array, map). -
indexis the integer index at each iteration in the loop. -
valueis the item in the collection at each iteration in the loop.
Example:
package "main"
import "fmt"
import "os"
func main() {
nargs := len(os.Args)
// counter controlled
for i := 1; i < nargs; i++ {
fmt.Printf("%s ", os.Args[i])
}
args1 := os.Args[1:]
// condition controlled
for len(args) > 0 {
fmt.Printf("%s ", args1[0])
args1 = args1[1:] // shift left
}
args2 := os.Args[1:]
// range controlled
for i, arg := range args {
fmt.Printf("%d %s\n", i, arg)
}
}
Break & Continue Statement
Break:
- Used inside a
for,switch, orselectstatement. - Breaks out of innermost loop in multiple
forstatements. - Can be used with labels.
Continue:
- Can only be used in
forstatement. - Continues with the next iteration of innermost loop.
- Skips remaining body of loop.
- Can be used with labels.
Example:
package main
import "fmt"
func main() {
for i := 1; i < 25; i++ {
if i % 2 != 0 { continue }
if i > 20 { break }
fmt.Printf("%d ", i)
}
}
This concludes the third part of the series. In next tutorial we'll cover functions and more, till then, Aloha.
Reach out to me here
Top comments (0)