Variables are one of the most important concepts in programming. There is so little you can do in programming without using variables. On the other hand, data types are different types of inputs that you can give your programs to work correctly. Finally, operators allow you to perform operations like adding numbers, concatenating strings, comparing variables, checking the validity of variables, and much more.
In the previous article, you learned about what Go is, the areas where it works best, and how to install Go and its VSCode extension on your system. In this article, you will learn about variables, data types, and operators in Go.
Prerequisites
To follow along with this tutorial, you only need to have a working installation of Go. Please read the previous article in this series to get up to speed.
Let's explore variables and how to use them in Go in the next section.
Variables in Go
Variables are used to store values that you intend to use multiple times in your code. They help you to build flexible programs as they enable you to define, use, and modify values in your application without having to memorize them. For example, you can define a name
variable with an initial value of "John"
. You can use that name anywhere in your code, change it to "Jane"
or any other name, and still use it with the name
instead of remembering what you changed it to every time you need the name.
There are multiple ways to define variables in Go; let's explore them in the following sections.
Create a Folder
To start writing Go code, create a folder with a name of your choice, open it in your code editor, and create a main.go
file inside it. We will write most of the code in this article inside the main.go
file.
Create a Main Function
Every Go application needs to have a main
function; this is the entry point of your application. Add the following code inside the main.go
file:
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
The code above declares the main.go
as part of the main
package, imports the fmt
package from Go's standard library, and creates a simple main
function that uses the Println
method on the fmt
package to print "Hello World"
.
Don't worry if you don't understand the code you wrote; things will become more apparent as you read.
Run the Application
There are several ways to run a Go application, but for the sake of simplicity, I will use the run
function in this article. Run the following command in the CLI:
go run .
The command above will run the main
function and return Hello World
in the CLI.
Typed Variables
As mentioned in the previous part of the series, Go is a statically typed language. This means variables in Go must have a specified type. You can define a typed variable like so:
var name string = "Adams"
The code above defines a name
variable with the value of "Adams"
using the var
keyword and type of string
. This type of variable definition is called a typed variable.
Automatic Type Inference
Go also allows you to omit the type keyword by using type inference to infer the type automatically. This means you can define a variable like so:
var surname = "Olabamiji"
The above code defines a surname
variable with the value "Olabamiji"
, which is also of type string
but I did not have to explicitly state the type because Go is smart enough to know the type using the automatic type inference.
Shorthand Declaration
You can declare variables in Go with even lesser code with the shorthand declaration syntax by using the colon and equals symbols (:=
) like so:
favHero := "Batman"
The code above declares a favHero
variable with the value of "Batman"
.
Note: The shorthand declaration syntax can only be used inside a function body, so the
favHero
variable should be inside themain
function.
Declaring Multiple Variables
Go allows you to declare multiple variables at once using parentheses with the var
keyword like so:
var (
age = 30
gender = "Male"
height = 1.75
weight = 75.0
)
The code above declares multiple variables using the var
keyword and parentheses. Go will infer the types of the variables inside the parentheses automatically.
Multiple Variables with One Liner
You can also declare multiple variables with a single line of code using a comma (,
) like so:
var favSong, favMovie = "The Way I Am", "The Dark Knight"
The code above declares the favSong
and favMovie
with a single line of code. The first value after the assignment operator (=
) will be assigned to the first variable name, and so on.
Let's make use of the variables inside the main
function. Add the following code inside the main
function:
fmt.Println("Mr.", name, surname, "is a", gender, "of", age, "years old. He is", height, "meters tall and weighs", weight, "kg. His favorite hero is", favHero, "and his favorite song is", favSong, "and his favorite movie is", favMovie)
The code above uses the Println
method to print out a sentence from the main
function. Next, run the application with the following command:
go run .
The command above will run the Go application and should return the following:
Clear the code inside the main.go
file, leaving just an empty main
function. Next, let's explore the different data types there are in Go.
Basic Types
Go supports three basic types and they are boolean
, numeric
, and strings
. Let's go over these types and how to use them effectively in the following sections.
Booleans
The boolean type, commonly referred to as bool
in Go, is represented with the true
and false
keywords. You can define a boolean in Go like so:
var isStudent bool = true
The above code declared an isStudent
variable with a value of true
.
Strings
A string
is probably the most used type in programming. It is defined by enclosing the text with double (""
) quotes. In fact, we've seen the string
type when we defined the first variable in this application. You can define a string
variable like this:
var name, surname string = "Adams", "Olabamiji"
The code above defined name
and surname
variables using the one-liner syntax you learned about in the previous sections.
Note: Unlike other languages, Go will throw an error if you define a
string
variable with single quotes (''
).
Numeric Types
In Go, there are several types for representing numbers and characters, each with its specific range and behavior. Here's a breakdown of each type and their differences:
int8
, int16
, int32
, int64
, int
: These are all integer types used to represent whole numbers. The number after the int
specifies the number of bits used to store the integer value. This means int8
uses 8 bits and int64
uses 64 bits. The int
type is the platform-dependent integer type, which means it will use the number of bits most efficiently for the underlying architecture.
uint8
, uint16
, uint32
, uint64
, uint
: These are similar to the integer types but unsigned, which means they can only represent positive values and not store negative ones.
float32
and float64
: These are floating-point types used to represent real numbers. float32
is a single-precision floating-point number that uses 32 bits, while float64
is a double-precision floating-point number that uses 64 bits. Double-precision floating-point numbers are more precise than single-precision numbers.
complex64
and complex128
: These types are used to represent complex numbers. complex64
uses two 32-bit floating-point numbers to embody a complex number, while complex128
uses two 64-bit floating-point numbers.
byte
: A byte
is an alias for uint8
. It is used to represent a single byte of data.
rune
: A rune
is an alias for int32
. It represents a Unicode code point, a unique number assigned to each character in the Unicode standard.
Overall, the main difference between these types is the range of values they can represent and their storage size. Choosing the appropriate type for a given variable depends on the specific requirements of the program and the values that need to be stored.
Next, let's create a sample of each numeric type. Add the following code to your main.go
file:
var (
// int8, int16, int32, int64
intVar int = -10
intVar2 int8 = -20
intVar3 int16 = 10
intVar4 int32 = -150
intVar5 int64 = 40000
// uint8, uint16, uint32, uint64
uintVar uint = 10787899999999999
uintVar2 uint8 = 134
uintVar3 uint16 = 19039
uintVar4 uint32 = 1234789000
uintVar5 uint64 = 100000
// float32, float64
floatVar float32 = -7980.909
floatVar2 float64 = 1789.089383
// complex64, complex128
complexVar complex64 = -908992920i
complexVar2 complex128 = 108798788i
// byte, rune
byteVar byte = 10
runeVar rune = -10
)
The code above defined all the numeric types in Go using the mutiple variable declaration with the var
keyword and parentheses. You can now use the variables inside the main
function like so:
fmt.Printf("These are the int types. intVar: %d\n intVar2: %d\n intVar3: %d\n intVar4: %d\n intVar5: %d\n\n", intVar, intVar2, intVar3, intVar4, intVar5)
fmt.Printf("\n")
fmt.Printf("These are the uint types. uintVar: %d\n uintVar2: %d\n uintVar3: %d\n uintVar4: %d\n uintVar5: %d\n\n", uintVar, uintVar2, uintVar3, uintVar4, uintVar5)
fmt.Printf("\n")
fmt.Printf("These are the float types. floatVar: %f\n floatVar2: %f\n", floatVar, floatVar2)
fmt.Printf("\n")
fmt.Printf("These are the complex types. complexVar: %f\n complexVar2: %f\n", complexVar, complexVar2)
fmt.Printf("\n")
fmt.Printf("These are the byte and rune types. byteVar: %d\n runeVar: %d\n", byteVar, runeVar)
Next, run the application with the following command:
go run .
The command above should run the application and return the following:
And that's it for the basic types that are available in Go. Let's explore the different types of operators and how to use them in Go in the next section.
Operators in Go
Operators in Go are used to perform different types of operations in your code. These include but are not limited to arithmetic operations, string concatenation, type conversions, comparisons, and combining expressions. Let's explore some of the major operators and what they are used for in Go.
Assignment Operators
Assignment operators are used to assign values to variables and constants. The two assignment operators in Go are =
and :=
. You used them to define variables in the previous sections. They can be used to assign anything to another.
For example, you can assign a variable to another variable like so:
input := 10
age = 20
input = age
fmt.Println(input)
The code above defined two variables, input
and age
, assign the age
variable to the input
variable, and print 20
which is the new value of input
.
Let's explore the arithmetic operators in the next section.
Arithmetic Operators
Mathematics is arguably the most important topic on the planet, so it is only normal for programming languages to allow users to do arithmetic operations. Arithmetic operators in Go are +
, -
, *
, /
, %
, and they can be used on all the numeric data types.
The Plus (+
) Operator
This operator is used to add multiple values of the same type together. For example, clear out the main.go
file and add the following code inside your main
function:
groceriesPrice, laundryPrice, phoneBillPrice := 100.50, 50.0, 200.0
fmt.Println("Total price:", groceriesPrice+laundryPrice+phoneBillPrice) // returns Total price: 350
The code above defines three variables, groceriesPrice
, laundryPrice
, and phoneBillPrice
, and prints the total value using the Println
method and the +
operator.
The Minus (-
) Operator
The minus operator is used to subtract a value from another value. For example, add the following code to your main
function:
salary, tax := 1000, 200
fmt.Println("Take home salary is", salary-tax, "after tax of", tax, "is deducted") // returns Take home salary is 800, after tax of 200 is deducted
The code above defines two variables, salary
and tax
, then prints out a "Take home salary is 800, after tax of 200 is deducted"
message after using the -
operator to deduct tax
from the salary
.
The Product (*
) Operator
This operator is used to return the product of two or more values. For example, add the following code inside the main
function:
kidsPackagePrice, noOfKids := 100, 5
fmt.Print("The total price of the kids package is: ", kidsPackagePrice*noOfKids, " Naira")
The code above declared two variables, kidsPackagePrice
and noOfKids
, then prints out a message and the product of both variables using the Print
function and the *
product operator.
The Quotient (/
) Operator
This operator returns the quotient of two or more values. For example, add the following code to your main
function:
noOfOranges, noOfKids := 150, 33
fmt.Println("Each kid gets", noOfOranges/noOfKids, "oranges")
The code above declared two variables, noOfOranges
and noOfKids
, then prints out a message and the product of both variables using the Print
function and the *
product operator.
The Remainder (%
) Operator
You guessed it! This operator returns the remainder after dividing two or more values. For example, edit the previous example to look like so:
noOfOranges, noOfKids := 150, 33
fmt.Println("Each kid gets", noOfOranges/noOfKids, "oranges,", "and there are", noOfOranges%noOfKids, "leftover")
The code above will print "Each kid gets 4 oranges, and there are 18 leftover"
.
Logical Operators in Go
Logical operators are used to compare boolean values. If you use an expression instead, Go will get the true
or false
from it and use it for the comparison. There are three logical operators in Go; we will explore them in the following sections.
The AND (&&
) Operator
The AND operator will return true
if both operands are true but will not evaluate the second operand if the first one returns false
. For example, if you only want to give a user access to the financial aid portal if they are over 18 and a student, you can do so in Go like this:
var isAdult, isStudent bool = true, true
if isAdult && isStudent {
fmt.Println("Congratulations! You can now access the student financial aid portal")
} else {
fmt.Println("Sorry! You are not eligible for the student financial aid")
}
The code above declares two variables, isAdult
and isStudent
, checks if both variables are true, then prints the first statement if they are both true and the second statement if one is false.
Note: Don't worry if you don't understand the
if
block yet. We will explore that part of Go in the next article.
The OR (||
) Operator
This operator will return true
if at least one of the operands is true. Using the previous example, if there had been an update and the school had removed the age limit for students that want to access the student financial aid, you can replace the &&
with the ||
operator like so:
var isAdult, isStudent bool = true, false
if isAdult || isStudent {
fmt.Println("Congratulations! You can now access the student financial aid portal")
} else {
fmt.Println("Sorry! You are not eligible for the student financial aid")
}
The code above checks if the user is a student or an adult before giving them access to the portal.
The NOT (!
) Operator
This operator checks if an operand is false. For example, if you want to give only students in the science department access to a hackathon portal, you can use the !
operator to check if a student is not a science student like so:
isScienceStudent := false
if !isScienceStudent {
fmt.Println("Sorry you are not eligible to participate in this hackathon")
} else {
fmt.Println("Congratulations! You are eligible to participate in this hackathon")
}
The code above defines a variable isScienceStudent
and checks if it is false before giving the user access to the hackathon.
That's it for logical operators. Let's explore comparison operators in the next section.
Comparison Operators in Go
These operators are used to compare two values. Go has six types of comparison operators, and we will explore them in the following sections.
The Equals To (==
) Operator
This ==
operator checks if two values are the same. For example, if you want to check if the input is equal to the saved password, you can do so using the ==
Operator. Add the following code to your main
function:
input, password := "wrongpassword", "password"
if input == password {
fmt.Println("Access granted")
} else {
fmt.Println("Access denied")
}
The code above defines two variables, input
and password
, checks if the given password equals the password, and returns a response based on the result. This Operator is arguably the most used in programming.
The Not Equals To (!=
) Operator
This Operator is used to check if two operators are not equal. Using the previous example, if you replace the ==
operator with !=
, the code will return "Access granted"
.
The Less Than (<
) Operator
This Operator is used to check if an operand is less than the second one. For example, if you want to enable withdrawals only when the account balance is greater than a certain amount, you can do so using this Operator in Go:
accountBalance, minimumBalForWithdrawal := 500, 1000
if accountBalance < minimumBalForWithdrawal {
fmt.Println("Insufficient funds")
} else {
fmt.Println("You can withdraw")
}
The code above defined two variables, accountBalance
and minimumBalForWithdrawal
, checks if the accountBalance
is less than minimumBalForWithdrawal
, and returns "Insufficient funds"
.
The Greater Than (>
) Operator
This operator is used to check if an operand is greater than the second one. Using the previous example, if you replace the <
operator with >
, the code will return "You can now Withdraw"
.
The Less Than Or Equal To (<=
) Operator
This operator checks if the first operand is less than or equal to the second operand. For example, if you want to check if the person applying for a grant is not older than 35 years, you can do so with the <=
operator like so:
inputAge, ageLimit := 22, 35
if inputAge <= ageLimit {
fmt.Println("Congratulations! You are eligible for this research grant")
} else {
fmt.Println("Sorry! You are not eligible for this research grant")
}
The code above defined two variables, inputAge
and ageLimit
, checks if the inputAge
is less than or equal to ageLimit
, and returns "Congratulations! You are eligible for this research grant"
.
The Greater Than Or Equal To (<=
) Operator
This Operator checks if the first operand is greater than or equal to the second operand. Using the previous example, if you want the person to be at least 18 years old, you can do so with the >=
operator like so:
inputAge, ageLimit := 22, 18
if inputAge >= ageLimit {
fmt.Println("Congratulations! You are eligible for this research grant")
} else {
fmt.Println("Sorry! You are not eligible for this research grant")
}
The code above checks if the inputAge
is greater than or equal to ageLimit
and returns "Congratulations! You are eligible for this research grant"
.
Now that you know the different comparison operators in Go, let's explore the increment and decrement operators in the next section.
Increment and Decrement Operators in Go
The increment and decrement operators are used to add and remove values. There are two increment operators and two decrement operators in Go.
Increment Operators
The two increment operators in Go are ++
and +=
. The ++
adds 1 to the value, while the +=
adds a specified number to the value. Here's an example:
age, weight := 10, 35.0
age++
weight += 3
fmt.Println("Age + 1 is", age, "while weight + 4 is", weight)
The code above created two variables, age
and weight
, added to them using the increment operators, and printed a message with the results.
Decrement Operators
The two decrement operators in Go are --
and -=
. The --
subtracts 1 from the value while the -=
subtracts a specified number from the value. Here's an example:
age, weight := 10, 35.0
age--
weight -= 3
fmt.Println("Age - 1 is", age, "while weight - 4 is", weight)
The code above creates two variables, age
and weight
, subtract from them using the decrement operators, and prints a message with the results.
That's it for the operators in Go.
Conclusion
Whew! That was a long one. Thank you so much for reading and I hope the article achieved its aim of teaching you everything you need to know about variable, data types, and the different types of operators in Go.
In the next article, we will explore control flow statements and loops in Go. Please leave your feedback, corrections, questions, and suggestions in the comment section, and I'll reply to all of them. Thanks again!
Top comments (0)