Tutorials / Go: From Basics to Production / Variables, types and constants

Variables, types and constants

13 min read go
Course contents (17 lessons)
  1. Getting started with Go
  2. Installing Go 1.25 and your first program
  3. Variables, types and constants
  4. Control flow: if, for and switch
  5. Functions, multiple returns and defer
  6. Slices and maps
  7. Arrays and slices
  8. Maps and working with strings
  9. Structs, methods and interfaces
  10. Structs, methods and pointers
  11. Interfaces
  12. Errors, packages and generics
  13. Error handling the Go way
  14. Packages and modules
  15. Generics
  16. Concurrency
  17. Goroutines and channels
  18. select, timeouts and context
  19. Mutexes, sync and the race detector
  20. Testing
  21. Testing and benchmarks
  22. Building and shipping a service
  23. Building an HTTP JSON API with net/http
  24. Building and deploying a Go service

Statically typed, but not wordy

Go is statically typed. Every variable has one type, fixed at compile time, and the compiler checks that you use it correctly. But Go also infers types, so you do not need to write them out all the time.

Declaring variables

package main

import "fmt"

const TaxRate = 0.17

const (
	StatusPending = iota // 0
	StatusPaid           // 1
	StatusCancelled      // 2
)

func main() {
	var shop string = "Murtaza Stationers"
	var quantity int
	var price float64 = 1250.5

	unit := "ream"           // short declaration, type inferred as string
	paid := false            // bool
	items, discount := 4, 10 // two variables at once

	quantity = items
	total := price * float64(quantity)
	totalWithTax := total * (1 + TaxRate)

	fmt.Println(shop, unit, paid, discount)
	fmt.Printf("subtotal %.2f, with tax %.2f\n", total, totalWithTax)
	fmt.Println("status:", StatusPaid, "zero value of int:", quantity-items)
	fmt.Printf("%T %T %T\n", shop, quantity, price)
}

Output:

Murtaza Stationers ream false 10
subtotal 5002.00, with tax 5852.34
status: 1 zero value of int: 0
string int float64

var versus :=

There are two ways to declare. var name type = value is the full form. Both the type and the value are optional, but you need at least one of them. The short form name := value declares and assigns in one step, and the compiler infers the type. The short form only works inside functions. At package level, outside functions, you must use var.

A common mistake: := declares a new variable. If you write it again for the same name in the same scope, you get "no new variables on left side of :=". Use plain = to assign to an existing variable. And be careful with shadowing: inside an inner block, x := 5 creates a new x that hides the outer one. The outer one stays unchanged. This catches people who then wonder why their value did not update, especially with err.

Basic types

TypeNotes
int, int64, int32...Whole numbers. int is 64 bits on modern computers.
uint, uint8 (byte)...Unsigned whole numbers. byte is another name for uint8.
float64, float32Decimal numbers. Use float64 by default.
stringImmutable text, stored as UTF-8 bytes.
booltrue or false.
runeA single Unicode character, an alias for int32.

For money, avoid floats. Store whole paisa or cents in an int64 and format when you print. Floats cannot represent most decimal fractions exactly.

Zero values

In Go, a variable declared without a value is not undefined. It holds the zero value of its type: 0 for numbers, "" for strings, false for bool, and nil for pointers, slices, maps, channels and interfaces. This design removes a lot of "uninitialised variable" bugs, and good Go code is written so that the zero value is useful.

No implicit conversions

Go never converts between number types for you. In the example, price * quantity would not compile, because one is float64 and the other is int. You must write price * float64(quantity). The compiler error is invalid operation: mismatched types float64 and int. It is irritating for the first week, and then you appreciate that no hidden conversion changes your numbers.

Converting a number to a string is a special trap. string(65) gives "A", the character with that code, not "65". To get the digits, use strconv.Itoa(65) or fmt.Sprint(65).

Constants and iota

A const is fixed at compile time. Untyped constants like TaxRate are flexible: they take the type needed when used. The iota keyword inside a const block counts upward from zero for each line, which is the standard way to make a set of related values, like an enum. In the example, StatusPending is 0, StatusPaid is 1 and StatusCancelled is 2.

Strings, bytes and runes

A string is a sequence of bytes. len("Lahore") is 6, but len("لاہور") counts bytes, not letters. To count characters, convert to []rune or use utf8.RuneCountInString. When you loop over a string with range, Go decodes characters for you.

for i, r := range "añb" {
	fmt.Println(i, string(r))   // 0 a, 1 ñ, 3 b: ñ takes two bytes
}

Printing with verbs

Common Printf verbs: %v default format, %+v structs with field names, %d integer, %.2f float with two decimals, %s string, %q quoted string, %T type, and %t bool. A wrong verb does not crash, it prints something like %!d(string=hello), and go vet will warn about it.

Try it yourself

Write a program that declares a product name, a unit price in paisa as int64, and a quantity as int. Calculate the total in paisa, then print it as rupees with two decimals using integer division and remainder: total/100 and total%100. Add constants for three order states using iota and print the numeric value of one of them.

go
package main

import "fmt"

const TaxRate = 0.17

const (
	StatusPending = iota // 0
	StatusPaid           // 1
	StatusCancelled      // 2
)

func main() {
	var shop string = "Murtaza Stationers"
	var quantity int
	var price float64 = 1250.5

	unit := "ream"           // short declaration, type inferred as string
	paid := false            // bool
	items, discount := 4, 10 // two variables at once

	quantity = items
	total := price * float64(quantity)
	totalWithTax := total * (1 + TaxRate)

	fmt.Println(shop, unit, paid, discount)
	fmt.Printf("subtotal %.2f, with tax %.2f\n", total, totalWithTax)
	fmt.Println("status:", StatusPaid, "zero value of int:", quantity-items)
	fmt.Printf("%T %T %T\n", shop, quantity, price)
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account