Video Coming Soon...
06: Basic Syntax: Variables
WARNING This exercise is in DRAFT status, so there may be errors. If you find any, please email me at help@learncodethehardway.com so I can fix them.
Every programming language needs a way for you to store data so you can work with it. They do this by creating a piece of memory in your computer that can fit the variable's size. If a variable is small integer it'll create a piece of memory that's 4 bytes, and a larger integer will be 8 bytes long.
You also need a way to reference (aka talk about) these pieces of memory in your code. Variables do both of these things. It tells the Go compiler, "Hey, reserve a piece of memory that's big enough for this integer and I want you to name it age
."
After this you can use the name in calculations to do math, control devices, read and write files, and make decisions.
How to Variable
In Go you can create variables 3 slightly different ways. First, you can use two steps to create a variable and give it a value like this:
var age int
age = 51
This first tells go to reserve memory for a variable named age
of type int
. It then gives that memory a value with age = 51
.
The second way to create a variable is to combine these two steps into one line:
var age int = 51
This does both the declaration of the variable and gives it a value at the same time.
Finally, there's a nice shorthand syntax that does this even easier:
age := 51
This is the same as the var age int = 51
line, and is more commonly used in Go. The only thing to remember with this form is after you do this once, you can't use it again on the same variable, so this is an error:
age := 51
age := 25
Instead you would do this:
age := 51
age = 25
Now lets use this knowledge to create some nonsense code to demonstrate this.
The Code
You'll learn about variables by typing in this code and getting it to compile. After you type it in I'll describe every line of code so you know what it does, but this is easier if you've "experienced" the code so we have something common to talk about. Think of this like me describing a painting that you've never seen vs. talking about a painting while we're both looking at it.
View Source file ex06/main.go Only
package main
import "fmt"
func main() {
var age int = 51
name := "Zed"
fmt.Println("My name is", name, "and I am", age, "years old.")
var hair string
hair = "Bald"
fmt.Println("I have a", hair, "hairstyle.")
}
Remember, and I'm only going to say this one more time, do not type out all of this code, compile it once, then cry about the millions of errors you get. Take it slow, type it in a little at a time, and let the Go compiler help you find errors.
WARNING As you do this though, also remember that Go complains about unused or missing variables. Use those to confirm that you are actually using the right variable, but ignore it if you haven't written the line that uses it yet.
Breaking it Down
I'll now explain each line one at a time:
package main
-- This tells the Go compiler that your code lives in the main package. You need at least one of these in the root directory of your project.import "fmt"
-- Import thefmt
package so you can print things to the Terminal.func main() {
-- This starts your code, and you can only have one of these in your whole program. You need the{
at the end of the line to start a "block". A "block of code" is just a group of lines that are connected to themain
function.name := "Zed"
-- Here we declare a variable using the:=
syntax which means "create the memory namedname
and give it the value"Zed"
.age := 51
-- Same again, but this time we tell Go this is an integer with a value of51
.fmt.Println("My name is", name, "and I am", age, "years old.")
-- This prints all of the variables to the screen with additional text. We'll explain functions in a later exercise but for now think of this as saying, "Heyfmt
! Println this stuff."var hair string
-- This is the other way to create a variable called "declaring a variable." You have to sayvar
, the namehair
, and then the type. We'll learn types in the next exercise.hair = "Bald"
-- This then assigned the string"Bald"
to that variable you declared.fmt.Println("I have a", hair, "hairstyle.")
-- Once again, tellingfmt
to print your variable.}
-- Finally, we end ourmain
function with a matching}
to the{
on thefunc main() {
. If you forget this you get an error.
"I Don't Understand It!"
If you feel this way that is totally normal. Programming is a complex topic so it's impossible to dump all the knowledge into your brain perfectly. We don't live in The Matrix after all. That means you only have a small piece of the overall puzzle, and you have to do your best to struggle to understand as you pick up more pieces.
Think of this as a mystery and you only have one clue currently. As the course progresses you'll slowly solve the mystery.
Break It
Error messages in every programming language are terrible. I'm not sure why but compiler people are probably the strangest folks on the planet. The Go compiler will frequently give you an error that has nothing to do with the actual error, tell you about errors on the wrong line, or give you an error that makes no sense.
It's very important that you start exposing yourself to errors as early as possible, and search for them online every single time you see one. This mostly the only way to "learn to speak weird errors."
Take the time now to remove random characters and see what kind of errors you get. Take notes on important ones and also look at where the error is reported vs. where it actually is in the code. Compilers will generally tell you an approximate location of an error, and if there's nothing obvious there then you have to look at previous lines to solve it.
Change It
A great way to practice using Go to create your own ideas is modifying someone else's code. It's also important to realize that you own the code now. Nothing is sacred and you have the right to take what I've written and change it how you want.
Take the time now and really mess with this code. Try to come up with the strangest ways to alter it and experiment. It's early for you so your experiments probably won't be correct but this is how you start learning what you can get away with in Go.
Remake It
The final practice you should do is to recreate this code from memory. When I say "from memory" I don't mean "memorize very character on every line for the next month." That's useless. What I mean is go back to Exercise 04 and write up a description of this code the same way I did in Exercise 04. Once you have that description delete your code and try to recreate it from just the description as I outline in Exercise 04.
You are definitely allowed to "cheat" if you can't remember something, so if you get stuck come back and look at my code to remember again. If you keep doing this you'll eventually build your ability to remember code and recreate it from descriptions of code.
Recreating code from memory is also a decent proxy for creating software from your own ideas. Your ideas are very similar to that description you wrote, so doing this practices creating software from nothing.
Finally, this exercise is for you if you ever say, "I could never do that on my own." Keep recreating software like this and eventually you will be able to create your own ideas from nothing.
Next Steps
Next we will learn about the various types Go has for storing data. This is important because Go is a "type safe language", which means it prevents you from doing things like trying to add an integer to a string. These types are also the building blocks of more complicated code and structures later.
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.