Golang: Variable Assignment & Data Types

Variable assignment and data types are those kind of topics that are absolutely necessary to cover. If we think about Python for a second, we can happily do this:

j= ‘Bob Smith’
j= 13

Here we have assigned a variable called j to be a string value of Bob Smith and then have immediately assigned the same variable as an integer value of 13. Python is cool with it, we’re cool with it, all works well and every one is happy. In Golang… not so.

Golang is a statically typed language which means once a variable is set to be a string data type, it cannot store anything other than strings.

To declare a variable in Golang, we have 2 options:

  • var variable_name datatype = value_to_assign
  • variable_name := value_to_assign

In the top example, we specifically tell Golang that we’re creating a string variable. You can see the implementation of that in the code snippet below.

In the second example, we use := which tells Golang to infer the data type. It’s a short hand way to define variables, so it’s one I prefer. An example would be: card := “Ace of Spades”. Both will result in a string variable being created, so it’s up to you which you prefer.

If you try to assign a value of 12 to our new string integer, you’ll get an error like: main.go:7:10: cannot use 12 (type untyped int) as type string in assignment. The good thing about Golang is that its error messages are actually quite useful, which is often not the case with error messages in other languages.