Tutorial for Go (Golang), Part 1

The Golang Gopher, courtesy of the Go website.

With Go or Golang ever-increasing in popularity and developer support, I find that there are not enough tutorials for Go, especially for ones starting up in the language. That is why I have decided on a multiple part series on learning Go from the ground up, everything that you need to know. Now, I feel some prior programming knowledge is required for this tutorial as I will assume that you know the basic programming concepts.

First, the boilerplate code. What’s necessary for any Go program is the main function. This tells Go where to start the program, and it will run from there.

package main

func main() {
print("Hello World!")
}

As you can see, I have a file that includes the main function in a package called main. This file is called main.go, but that is not necessary to have it in a main.go file. The file with this main function can be called in any file. Notice that there are no semicolons; one of the concepts that it borrows from Python is that a new line is a new statement, and a comma continues the existing statement.

package main

func main() {
i := 0
if i < 0 {
print("i is less than zero")
} else if i > 0 {
print("i is greater than zero")
} else {
print("i is equal to zero")
}

}

This is some code for if-else statements. Also, notice the unique way of instantiating a variable: no type, the colon and equals sign, and no semicolon at the end. As you can see, we have declared i to be zero, and then went through each if statement to print a statement regarding the condition of the variable i. There is no declaration of the type of i, and the type is dynamically generated. The if-else statements are the same as Java without the parentheses.

package main

func main() {
i := 0
for i < 1000 {
if i > 0 {
i += i
} else {
i += 1
}
}

}

The for-loops in Go follow the principles for if-else statements: no parentheses and the condition at the top. You might notice that it does not really follow any other principles and seems more like a renamed while loop. And, you are correct: the while loop in C is the for loop in Go. So for both while loops and for loops, there is only one type of loop, which is a for loop.

Thanks for reading Part 1 of this tutorial. Please make any comments or suggestions on improvements.

EDIT: Part 2 is now up. Here’s the link: https://goo.gl/os2cDq