As with all programming languages, there’s a plethora of options available to write the software or automation that you’re hoping to accomplish, which can get cumbersome for new programmers or someone that’s new to a language. Luckily, there’s always a place to start in terms of getting yourself up to speed with a new language. For example, all languages have components like variables and functions, which means you can take what you learn from one language and utilize it in another.
In this blog post, you’ll learn a few methods you can start today to get yourself familiar with Go.
Basic Functions
Functions, at a high level, are the building blocks of your code. They are what contain the “thing” that your code is going to do. Is your code going to return hello world
? Is it going to authenticate to AWS? Is it going to build robots to take over the world?
A Go code file with a function inside of it contains:
- The
package
keyword followed by the package name. If you seemain
as the package name, that means the Go file you’re working with is the entry point into the application stack. Themain
package is what’s used to run all of the sub packages. If you’re writing a script or some automation code, chances are your code logic will be inside of themain
package. - The
import
keyword is how you can use standard and third-party libraries in your code. For example, thefmt
package used in the below code allows you to perform various pieces of functionality, including the ability to print something (like a string) to the terminal/console. - The
func
keyword defines a new function followed by the function name. In the example below, it’s calling themain
function, which is typically used as the entry point into child/sub functions which you’ll learn about in the Advanced Functions section of this blog post.
One important piece of information to keep in mind is when you define a main
package, it must have a main
function inside of it. The main
package is what’s run by something like the go run
command. Packages that don’t have main
inside of them aren’t run directly, they’re run from the main
package. if you try to run a main
package without a main
function, you’ll get an error similar to the one below.
function main is undeclared in the main package
Below is an example of a basic Go function.
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
Advanced Functions
In the previous section, you saw how functions are created by putting most of the code logic inside of the main
function. Although you may see this for various scripts and automation capabilities, chances are you won’t see the main function used as the function that holds the core logic of the code. Instead, you’ll most likely see the core code logic inside of a child function.
Child functions are functions that are created outside of the main
function and are usually called upon by the main
function. Why? The short answer is that Go is a functional-based programing language. It doesn’t utilize methods or classes, it utilizes functions for all of its capabilities. The main
function, much like the main
package, is the entry point into the code. You can use the main
function to call upon the child function(s).
Taking a look at the example below, you can see that the testing()
function is called upon from the main
function. The main
function then runs the testing()
function.
package main
import "fmt"
func main() {
testing()
}
func testing() {
fmt.Println("hello from the testing function")
}
Variables
After learning functions, the next logical step is to learn variables. Variables are a location in which you can save data that will change over time in memory instead of hard coding the value somewhere in your code.
For example, let’s say you have a cloud region that may change at some point based on where your code is running. If you hard code something like us-east-1
into your code, that means every time you run the code outside of us-east-1
, you have to go through the code and change it. It’s a major hassle.
Instead, you can create a variable that contains the value us-east-1
and only change the value once while using the variable throughout your code.
For example:
region := "us-east-1"
The variable is stored in memory, which means it’s ephemeral and you can always change the value based on how and where it’s running.
In this section, you’ll learn about three primary ways to create variables in go.
Shorthand
When you see a variable created in Go, you’ll typically see it look like the following:
sayhi := "hello world"
The sayhi
part is the key and the "hello world"
part is the value (hence key/value pairs). The colon followed by the equals sign (:=
) means a variable is being defined.
An example of the shorthand variable inside of a Go function is below.
package main
import "fmt"
func main() {
sayhi := "hello world"
fmt.Println(sayhi)
}
Full
Although 9 times out of 10 you’ll see the shorthand variable used, there’s also the longhand/full variable.
The full variable contains:
- The
var
keyword - The name of the variable
- The variable type (string, int, float, etc.)
- The value
A lot of engineers like the full variable because it tells you and defines exactly what the variable type should be, which saves a lot of time in troubleshooting later on when the proper value isn’t returned as expected. Go is a statically typed language, which means whatever type you specify is the type that must be returned. You’ll learn more about that in the Return Types section of this blog post.
package main
import "fmt"
func main() {
var sayhi string = "hello world"
fmt.Println(sayhi)
}
Global
The last way in which you can create a variable is the global variable. Notice how with the code example below, the sayhi
variable is outside of the function scope. The reason why is that you may have a time when you want to use the same variable inside of multiple functions. If the variable exists inside of a function, its value is tied to that function only. However, if the variable is outside of the function, it’s a global variable and can be used throughout your code.
package main
import "fmt"
var sayhi string = "hello world"
func main() {
testing()
testing2()
}
func testing() {
fmt.Println(sayhi)
}
func testing2() {
fmt.Println(sayhi + " again")
}
Constants
A constant is essentially a variable that’s hard-coded. It’s a value that can never change. With a variable, you can define the value in one part of the code and then change the value of the same variable in another part of the code. With a constant, the value can never change.
It’s similar to a tuple
in Python if you’re familiar.
The code example below shows an example of a constant inside of a main function.
The constant is initialized by using the const
keyword. Notice how it looks almost identical to the longhand variable. The only different is you’re specifying the const
keyword instead of the var
keyword.
package main
import "fmt"
func main() {
const hiagain string = "hello world"
fmt.Println(hiagain)
}
Return Types
For the last section of this blog post, you’ll learn about what it means to return a specific value. When you return a value, it means that you’re specifying inside of your code what the function should be returning. Is it returning a string? An int? Some output of the code to be used later on?
When specifying a return, you’ll use the return
keyword followed by what you want to be returned from the function. Please note that when you return a value like in the code below, you’re not specifically printing output to the screen. You’re simply taking that returned value to be used later on.
For example, perhaps you’re using a Go function to initialize a connection to a Kubernetes cluster. You then use said function to connect to the Kubernetes cluster when you’re running a specific task in your code. If you want to use Go to create a Kubernetes Pod, you would have to connect to the cluster, and you can do that by creating a function that connects to the cluster and returns the Kubeconfig.
Because Go is a statically typed language, the return type must match the value that’s being returned. For example, if you specify string
as the return type and try to return an int
, you’ll get an error that indicates a “type mismatch”.
package main
import "fmt"
func main() {
name("Mike")
}
func name(name string) string {
fmt.Println(name)
return name
}
Conclusion
Go is an amazing programming language for anything and everything system-related, application-related, and automation-related. It’s a language that certainly has a “one size fits all” feeling and can be used for just about anything. If you’re working with Kubernetes, it’s a great language to know as Kubernetes is written in Go.
Top comments (1)
Nice article, also might be useful to mention that go offers the possibility of returning multiple values, and if your function has named return values you can use naked return e.g:
and usage