How to Declare a Variable in Go

Alissa LozhkinAlissa Lozhkin
2 min read

Variables are super important for coding, and declaring one is one of the first things you should know how to do when learning a new programming language.

In Go, this is very easy to do. You simply use the keyword 'var'. To declare a variable without assigning a value to it right away, you can write the following:

var abc string

The code above defines a string variable called 'abc'.

We can just as well use this syntax to assign a value to the variable:

var abc string = "Hello"

The code above defines a string variable called 'abc' with the value "Hello."

You can also declare and assign without specifying the datatype of the variable by writing something like this:

var abc = "Hello"

In the code above, it is left to the compiler to figure out the datatype of the variable 'abc'.

There is another syntax that can be used for the declaring and assigning of a variable:

abc := "Hello"

The ':=' notation is used instead of 'var'. Note that this notation can only be used when first declaring a variable. If you want to assign 'abc' another value later on, you should use '=' and not ':='.

One final note on variables: they are designed to be mutable so you can change the value of them. However, the datatype of the variable cannot be changed.

0
Subscribe to my newsletter

Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alissa Lozhkin
Alissa Lozhkin

My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin