Declaring Variables in Go

By TechCogs | Programming and Coding | 25 Feb 2020


Declaring variables is one of the most fundamental things in any programming language, and declaring variables in Go is a little different than in languages like C++ or Java.  In languages like C++ and Java you declare the variable type first followed by its name, such as "string name;".  This is a string variable named name.

In Go it's the other way around.  To declare a variable of type string called name in Go, you do it like this.

var name string

You can read this by saying, "Name is a string".  If you want to initialize this string to a beginning value it's done in the familiar way.

var name string = "Some Name"

In fact, just like using the "auto" keyword in C++, the Go compiler can infer the type of the variable above so we can omit the string declaration and write it like this.

var name = "Some Name"

Go will know that the "name" variable is a string just from how it's being assigned to.  Keep in mind though that once the type of a variable is inferred, it keeps that type for the rest of the program.  For instance one the "name" variable is inferred as being a string you can't change it to an int or some other type later.

Another way to declare and initialize a variable all at once is using the ":=" operator.  For something simple like a string it might not have many advantages over using the var keyword, but it can come in handy when dealing with more complex types and data.

name := "Some Name"

Even if declaring variables in this way seems unfamiliar at first, once you use it for a while it becomes very comfortable.

How do you rate this article?

3


TechCogs
TechCogs

I work with Linux, technology, computers, and science.


Programming and Coding
Programming and Coding

The wonderful world of software engineering and software creation, centered around languages like D, Java, Python, Dart, and C++.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.