Learn The Go Programming Language — Conditional & Loops
There are conditional statements in almost every programming language that enable you to determine whether one piece of code should be run over another. There is no exception to this rule in Go.
It is also possible that some parts of your code will need to run repeatedly. The Go programming language provides loops that run sections of code repeatedly.
Comments
The most common form of comment is marked with two slashes (//). A comment includes everything from the slashes to the end of the line.
// Total count
var count int
A block comment is a form of comment that spans multiple lines, which is less commonly used. Block comments start with /* and end with */ and everything between those markers is part of the comment.
/*
* Total count
* present in program
*/
Multiple return values from a function or method
In most programming languages, functions and methods can only return one value, but in Go, they can return any number of values. In Go, multiple return values are most often used to return an error value that can be used to determine if anything went wrong while the function or method was running. As an example,
duration, err:= time.ParseDuration("430m")
bool, err := strconv.ParseBool("true")
Go does not allow us to declare a variable unless we use it.
Each variable declared in Go must also be used somewhere in your program. Our code will not compile if we add an err variable and do not check it. The presence of unused variables is often an indication of a bug.
This program won’t compile and the following error will come.
err declared but not used
How to resolve this error?
Options 1: Ignore the error return value with the blank identifier
Go’s blank identifier can be used when we don’t intend to use a value that is normally assigned to a variable. By assigning a value to the blank identifier, it is essentially discarded. In an assignment statement, simply type an underscore (_) character where you would normally type the variable name.
Option 2: Handle the error
Our program would proceed anyway, even with invalid data, if we received an error from the time.ParseDuration function. When an error occurs, it would be better to alert the user and stop the program.
This can be done with the Fatal function in the log package, which logs a message to the terminal and stops the program at the same time.
$ go run duration_err_handle.go
2022/10/16 12:10:55 time: unknown unit "minutes" in duration "430minutes"
exit status 1
Conditionals
In the previous example, we checked that err was nil, and if there was an error we logged the error and exited.
The conditional statements cause a block of code to be executed only if a condition is met. A conditional block body executes code if the result of an expression is true. The conditional block is skipped if it is false.
Go supports multiple branches in the conditional, just as most other languages do. The statements are in the form of if-else statements.
if count == 0 {
fmt.Println("No visitor")
} else if count <= 80 {
fmt.Println("Visitors are coming in good numbers")
} else {
fmt.Println("Almost housefull now")
}
Using the && operator, you can run some code only if two conditions are true. The || operator can be used if either of two conditions is true.
Methods
A method in Go is a function associated with a value of a given type. There are some similarities between Go methods and the methods attached to objects in other object-oriented programming languages, but they are a bit simpler.
In the time package, a Duration represents the elapsed time between two instants as an int64 nanosecond count. Time.Duration has an Hour method that returns the duration as a floating point number.
The time.ParseDuration function returns duration, which we store in the duration variable. On the value that duration refers to, we call the Hours method. We print the floating point hours returned by the Hours method.
Methods are functions that are associated with values of a particular type.
Avoid shadowing names
A variable named error would shadow the name of a type called error. Make sure a variable doesn’t have the same name as any existing functions, packages, types, or variables. Shadowing occurs if the same name already exists in the enclosing scope.
fmt.Println undefined (type string has no field or method Println)
Blocks & Variable Scope
Every variable you declare has a scope, a portion of your code within which it can be seen. Variables declared within a scope can be accessed anywhere, but if you try to access them outside of that scope, an error will occur.
A variable’s scope is the block it’s declared in and any blocks nested within it.
Compilation errors occur when the same variable name is declared twice in the same scope. A short variable declaration is allowed as long as at least one variable is new. The names of the new variables are treated as declarations, while the names of the existing variables are treated as assignments.
val1 := 10
val2, val1 := 20, 30
fmt.Println(val1, val2)
// output
30 20
Loops
Using a loop, we can execute a block of code repeatedly. Loops are probably familiar to you if you’ve worked with other programming languages.
for i:=0; i<=10; i++ {
fmt.Println("index value", i)
}
The “for” keyword is always used at the beginning of a loop. In one type of loop, for is followed by three segments of code.
- Variables are usually initialized with an initialization statement.
- When to break out of a loop, a condition expression is used.
- The post statement runs after each loop iteration.
Init and Post Statements Are Optional
In a for loop, you can omit the init and post statements, leaving only the condition expression.
i:=0
for i<=10 {
fmt.Println("index value", i)
i++
}
Skipping parts of a loop with continue & break
A loop in Go can be controlled by two keywords. By default, the continue method skips to the next iteration of the loop without running any further code.
Break, the second keyword, breaks out of a loop immediately. There is no further execution of code within the loop block, and no further iterations are performed.
$ go run loop.go
index value 1
index value 3
index value 5
index value 7
Summary
- Everything from a // marker to the end of the line is ignored by Go.
- Multiline comments begin with /* and end with */. Newlines and everything in between are ignored.
- In contrast to most programming languages, Go allows multiple return values.
- A common use of multiple return values is to return the main result of the function along with an error value.
- The _ blank identifier can be used to discard a value without using it. In any assignment statement, the blank identifier can be used instead of any variable.
- Methods are functions associated with types of values.
- If you name a variable the same as a type, function, or package, it will shadow the item with the same name.
- Blocks of code are enclosed in {} braces in functions, conditionals, and loops.
- The scope of a variable is limited to the block it is defined within, and all blocks nested within that block.
- The continue keyword skips to the next loop iteration.
- When you use the break keyword, you exit out of the loop completely.