Introduction
I hope everyone enjoyed their holidays or time off, if you had it. I am just finishing up two weeks of time off and I can say it will be very difficult to get back into the work schedule again. I have been sleeping in till 6AM every day and it has been so wonderful. I am not looking forward to those 3:30AM wakeup calls again.
My adopted puppy has been keeping me very busy. He needs a lot of training since he is pretty much scared of everything. He’s especially scared of certain women, but I haven’t been able to find a commonality between them! He will growl at them if they get close to him and then hide behind me. I wonder what happened to him early on in his life? I’m trying to give him treats whenever we pass people so he associates people with something good. In between dog training and sleeping in (not such a bad life!), I’ve still been practicing Go everyday. Here are some additional things I have learned after leaving off at variables.
Functions Review
Functions are a group of one or more lines of code that you can call from other places in your program.
Here is an example:
package main
import (
"fmt"
"strings"
)
func main() {
myLowercaseString:= "i am lowercase"
fmt.Println(strings.ToUpper(myLowercaseString))
}
The strings package has a ToUpper function that is called on the string myLowercaseString. The strings.ToUpper function takes one or more arguments (what you want the function to work with) , in this case, myLowercaseString and returns a string with uppercase letters. We then use the Println function to print out the result. Recall that you access functions by typing in the package name, a dot, and then the function from the package name that we want to use:
fmt.Println()
strings.ToUpper()
Functions expect that their arguments are of a particular string. For example, the string.ToUpper function expects a string. If I set myLowercaseString := 1234 and run this program again, the following error is returned:
fritzie@underacloud GoPractice % go run functions.go
# command-line-arguments
./functions.go:10:30: cannot use myLowercaseString (variable of type int) as type string in argument to strings.ToUpper
Methods
Unlike Python, Go does not have classes. However, you can use methods. Methods are functions that are associated with values of a given type. Methods are similar to “objects” in other languages. Functions belong to packages and methods belong to individual values. The value is the item that appears to the left of the dot.
Go’s time package has a number of date and time related functions that can be used to represent a specific point in time using the time.Time type.
Here is an example of using methods from a package:
package main
import (
"fmt"
"time"
)
func main() {
timeInSeattle := time.Now()
fmt.Println("The current time in Seattle is" , timeInSeattle)
fmt.Println("The year is", timeInSeattle.Year())
fmt.Println("The month is", timeInSeattle.Month())
}
In the above example, we import the time package so we can use the time.Time type.
In this example, timeInSeattle is the value and Year and Month are the method names.
A variable called timeInSeattle is created and it calls the time.Now function and returns the current data and time. Then we use the time.Time Year and time.Time Month methods to return the year and month. If we run this program, we get the following output:
fritzie@underacloud GoPractice % go run functions.go
The current time in Seattle is 2022-12-31 11:34:44.896543 -0800 PST m=+0.000200543
The year is 2022
The month is December
Conditional Statements
You can use conditional statements to cause a block of code to be executed only if a condition is met.
For example:
if year == 2023 {
fmt.Println("Happy New Year!")
}
The conditional statement starts with the word if and then the condition (year == 2023), followed by the start of the conditional block ({). The conditional block comes next (fmt.Println(“Happy New Year!”)), followed by the end of the conditional block (}).
If the expression evaluates to true (year is 2023), then the conditional block body is executed. If it is false, then the conditional block is skipped.
You can use the following in your conditional statements.
-
if – to specify a block of code to execute if a specified condition is true
-
else – to specify a block of code to execute if the same condition is false
-
else if – to specify a new condition to test if the first condition is false
If Statement – if a condition is true, execute specified code
num1 := 30
num2 := 45
if num1 < num2 {
fmt.Println(num1, "is less than", num2)
}
What do you think prints out when you run this?
If you said “30 is less than 45”, than you are correct!
If Else – if the condition is false execute else statement
num1 := 300
num2 := 45
if num1 < num2 {
fmt.Println(num1, "is less than", num2)
} else {
fmt.Println(num1, "is bigger than", num2)
}
Since num1 is greater than num2, the if statement is false and the else statement is executed instead. This prints “300 is bigger than 45”.
Else If – if the first condition is false, check the next condition (or conditions)
num1 := 300
num2 := 300
if num1 < num2 {
fmt.Println(num1, "is less than", num2)
} else if num2 > num1 {
fmt.Println(num1, "is bigger than", num2)
} else {
fmt.Println(num1, "and", num2, "are equal")
}
}
Here num1 and num2 are equal. The first statement will be false and then the else if statement will run. The else if statement will also be false. The final else statement will run and print “300 and 300 are equal”.
Relational Operators
Relational operators are used for the comparison of two values. Go supports the following relational operators:
< Less than – checks whether the first operand is less than the second operand. If so, return true.
<= Less than or equal to – checks whether the first operand is less than or equal to the second operand. If so, return true.
> Greater than – checks whether the first operand is greater than the second operand. If so, return true.
>= Greater than or equal to – checks whether the first operand is greater than or equal to the second operand. If so, return true.
== Equal to – checks whether the two operands are equal to each other. If so, return true.
!= Not equal to – Checks whether the two operands are equal or not. If not, return true.
What will the following code return?
num1 := 300
num2 := 3
fmt.Println("Is num1 < num2 ?", num1 < num2)
fmt.Println("Is num1 > num2 ?", num1 > num2)
fmt.Println("Is num1 <= num2 ?", num1 <= num2)
fmt.Println("Is num1 >= num2 ?", num1 >= num2)
fmt.Println("Is num1 == num2 ?", num1 == num2)
fmt.Println("Is num1 != num2 ?", num1 != num2)
The above results in the following:
fritzie@underacloud GoPractice % go run conditions.go
Is num1 < num2 ? false
Is num1 > num2 ? true
Is num1 <= num2 ? false
Is num1 >= num2 ? true
Is num1 == num2 ? false
Is num1 != num2 ? true
Logical Operators
Logical operators are used to combine two or more conditions and determine the logic between values. The logical operators in Go are:
&& Logical And – returns true when both the conditions are true.
|| Logical Or – returns true when one or both of the conditions are true.
! Logical Not – reverses the result and returns false if the result is true
Here is an example of using logical operators:
num1 := 1
num2 := 3
fmt.Println("Is num1 < 5 && num2 < 5 ?", num1 < 5 && num2 < 5)
fmt.Println("Is num1 < 3 || num2 < 3 ?", num1 < 3 || num2 < 3)
fmt.Println("Is num1 != 100 ?", num1 != 100)
This will print the following results:
fritzie@underacloud GoPractice % go run conditions.go
Is num1 < 5 && num2 < 5 ? true
Is num1 < 3 || num2 < 3 ? true
Is num1 != 100 ? true
Conclusion
Additional Note:
In Go, every variable that is declared must be used somewhere in your program. You can use Go’s blank identifier to assign a value to a variable that we do not intend to use. The blank identifier can be used by typing an underscore (_) character in an assignment where you would normally type a variable name.
This post covered methods, conditional statements, relational operators, and logical operators. Now we know enough to start creating some programs with flow control. Next – I’ll come up with an exercise to cover what I went over today. Stay tuned!