Going from Swift to Go: Creating Variables

Going from Swift to Go: Creating Variables

Jumping from the Swift programming language to the Go programming language is easy, as I discovered. But how does creating variables compare?

Variable Declaration (without assignment)

In Swift, first we declare whether the variable will change or not, so we choose let or var. Second, we choose a variable name, followed by some semicolons and the type of the variable. Example: var myNumber : Int? . Note that we have to add a ‘?’ to make this an optional, because Swift only allows variable declaration by itself if the variable is optional.

In Go, the variable is expected to change, so we start with ‘var’, then choose a variable name, and finally declare the variable type. Example: var myNumber int.

Variable Assignment

In both Swift and Go, the syntax is the same: variable = assignment. For example, myNumber = 3.

Variable Declaration and Assignment (short version)

In Swift, we begin by declaring whether the variable can change, using ‘let’ or ‘var’, then do the same as variable assignment. Example: let myNumber = 3.

In Go, we start with the variable name, and then use ‘:=’ followed by the assignment. Example: myNumber := 3.

Variable Declaration and Assignment (long version)

Sometimes, you may want to specify a variable type, instead of implying it. For example, if you know the compiler will interpret an unspecified variable as a float, but you want it to be a double.

In Swift, we take the short version, let myNumber = 3 , and add a scodeicolon followed by the variable type after the variable name. Example: let myNumber : Int = 3 .

In Go, we take the variable declaration and add = assignment. Example: var myNumber int = 3 .