Variables and Constants in Go Programming

Learn about various data types in Go, how to declare a variable and how `:=` notation work for type inference

Uday Hiwarale
Jul 8, 2018 · 7 min read

Variables & Data Types

What is a variable?

A variable is a storage unit of a particular type. You can give a name to this storage unit. A variable must be defined with a type of data it is holding. For example, string is a data type provided by go to store strings.

Data types

There are several data types in Go. These are as following

Zero value

Unlike other programming languages where variables hold null or undefined values when not initialized with any value, Go gives them zero-value of their respective types. As from the above table, boolean gets false value and integer gets 0 value.

Declaring a variable

To declare a single variable, you must follow the following syntax.

var variableName dataType = initialValue

initialValue is optional. If you do not give initial value to variable assignment, it will hold zero-value of its data type.

var integer1 int = 15
var integer2 int8 = -25
var integer3 int32
var float1 float32 = 63.2
var string1 string = "Hello World!"
var boolean1 bool
var boolean2 bool = true

You can later assign or re-assign any value to a variable. You must follow the following syntax to reassign a new value to a variable.

variableName = newvalueinteger1 = -15
integer2 = 25
integer3 = 965
float1 = -52.99
string1 = "Hello There :)"
boolean1 = true
boolean2 = false

Variable name convention

Go recommends writing variable names in simple word or camelCase. Even under_score variable names are valid, they are not idiomatic.

Type inference

Even when Go is statically typed language, Go provide us ease to eliminate declaration of data type while declaring a variable. You can drop data type from variable declaration like below

var variableName = initialValue

Go will pick up data type from the initialValue. Hence this syntax will only work when you are assigning some initial value to a new variable.

var integer1 = 52 //int
var string1 = "Hello World" //string
var boolean1 = false //bool

Short-hand notation

Go also provide one shorthand syntax to declare a variable. In this syntax, you can drop var and dataType.

variableName := initialValue

Go when finds := assignment syntax, it understands that new variable needs to be declared with an initial value.

integer1 := 52 //int
string1 := "Hello World" //string
boolean1 := false //bool

Multiple variable declarations

You can declare multiple variables of a single type in a single statement like below

var var1, var2, var3 int

You can assign initialValue to above syntax

var var1, var2, var3 int = 1, 2, 3

You can also drop data type and let Go use type inference to guess data type. This way you can declare multiple data types variable on a single line

var var1, var2, var3 = 1, 2.2, false

You can also use short-hand notation instead of the above statement

var1, var2, var3 := 1, 2.2, false

You can also use multiple lines to declare a variable of different types with a single use of var keyword

var(
    var1 = 50
    var2 = 25.22
    var3 string = "Telefonía"
    var4 bool
)

More on short-hand notation

The shorthand notation syntax := can only be used inside the function body. Also, it can only be used when at least one of the variables on the left side of := is newly declared.

Shorthand syntax will come in handy when new variable declares will get value at run-time, for example, a value receives from the function call (example below).

package mainimport (  
    "fmt"
    "math"
)func main() {  
    a, b := 145.8, 543.8
    c := math.Min(a, b)
    fmt.Println("minimum value is ", c)
}

Type conversion

In Go, you can not add, subtract (or do any kind of mathematical) operation on variables to two different data types. Hence variables first must be converted to the same data type. In Go, this is very simple. Just wrap any variable inside parenthesis with data type prefix that you want to convert that variable into. The syntax to convert data to a type is type(var).

var1 := 10 // int
var2 := 10.5 // float// illegal 
// var3 := var1 + var2// legal
var3 := var1 + int(var2) // var3 == 20

Type conversion is very important when variable of different types are used in mathematical expression. Go does not allow variables of different types to be used as operand in mathematical expression.

Type aliasing

You can pretty much declare alias to any built-in or user-defined type using a simple syntax

type aliasName aliasTo

In the above syntax, aliasName is the name you want to give it to your type which will behave like aliasTo type.

For example, if you want to define your own type myInt which behaves exactly like int32 then you can define it like

type float float64

In the above program, Go will create float type which will be duplicate of the type float64. You can use this type as a normal Go type and declare variables. As there is no float built-in type in Go and I hate typing float64, I usually do this more often.

Let’s see newly defined float type in action.

package mainimport "fmt"type float float64func main() {
	var f float = 52.2	fmt.Printf("f has value %v and type %T", f, f)
}

In the above program, we have defined the type float as an alias to float64 type and created a variable f of type float of initial value 52.2.

Above program yields below result

f has value 52.2 and type main.float

Above program prints main.float because float is a custom type and it must belong to a package. Type can be defined anywhere in the program, like in a function or a condition block.

If you define a type alias with the initial letter in small caps, then it won’t be exported from the package and other packages won’t be able to use it.

Also, in the above program, float won't be comparable to float64 as even they share the same properties, they still are different types. Hence if you define two variables with these types, they won't be comparable.

package mainimport "fmt"type float float64func main() {
	var f float = 52.2
	var g float64 = 52.2	fmt.Println("f == g", f == g)
}

So, above program won’t compile and compiler with throw compilation error

invalid operation: f == g (mismatched types float and float64)

What is a constant

Constant is a variable in Go with a fixed value. Any attempt to change the value of a constant will cause a run-time panic. Constant must be declared with const keyword and an initial value.

const const_name [data_type] = fixed_value

data_type is optional as go will infer data type from fixed_value.

In Go, constant value must be known during compile time. If you are trying to assign value returned by a function call, that won’t work. const a = math.Sqrt(4) is an illegal statement as value of a is computed during run time.

Multiple constants declaration

Like variables, multiple constants can be declared in one statement.

const const_1, const_2 = value_1, value_2

Or you can follow multiple line syntax

const(
    const_1 = value_1
    const_2 = value_2
)

In a parenthesized const declaration expressions can be implicitly repeated -this indicates a repetition of the preceding expression.

const(
	a = 1 // a == 1
	b = 2 // b == 2
	c     // c == 2
	d     // d == 2
)

iota

Go provides a keyword iota that can be used when declaring enumerated constants. This keyword yields an incremented value by 1 starting from 0, each time it is used.

const(
    a = iota // a == 0
    b = iota // b == 1
    c = iota // c == 2
    d        // d == 3 (implicitely d = iota)
)

Use _ (blank identifier) to skip a value. _ will receive the value of iota + 1 but will save the value to garbage.

const (
	a = iota + 1 // a == 1
	_            // (implicitly _ = iota + 1 )
	b            // b == 3 (implicitly b = iota + 1 )
	c            // c == 4 (implicitly c = iota + 1 )
)

Numeric Expressions

Numeric constants are free to be mixed and matched in expressions and a type is needed only when they are assigned to variables or used in any place in the code which demands a type.

But the result of any mathematical expression depends on the data type of operands. For example, the division of two integers will be an integer.

var a = 11/2 // a == 5

This happens as both operands hold data type of int. If you change any of the operand's data type to float, result will be a float value.

var a = 11.0/2 // a == 5.5
var b = float32(11)/2 // a == 5.5

Run Go

A place to find introductory Go Programming Language tutorials and learning resources. Like my other tutorials on Web Development, Run Go publication features important Go articles with deep dive into core of the language with examples and sample code.

Uday Hiwarale

Written by

Software developer and Technology enthusiast from India. Collab with me at github.com/thatisuday | Support my work by contributing at paypal.me/thatisuday

Run Go

Run Go

A place to find introductory Go Programming Language tutorials and learning resources. Like my other tutorials on Web Development, Run Go publication features important Go articles with deep dive into core of the language with examples and sample code.