Variables and Constants in Go

By Syncfusion®, Inc. · Last updated

How to declare, initialize and change variables with var and :=, make constants with const and iota, name things, and ignore values with the blank identifier.

What Are Variables?

Variable = a named box in memory that holds a value.

  • The name lets you find the box again.
  • The value is what is inside the box now.
  • The value can change while the program runs.

For example:

  • name holds "Asha"
  • marks holds 92
  • passed holds true

Simple lesson: a variable is a labelled box that keeps a value for your program.

A Real-World Example

Think of the school library register.

  • Each row has a label: Book, Student, Due date.
  • The librarian writes a value next to each label.
  • When the book comes back, she rubs out the due date and writes a new one.

Now the mapping:

  • Label = the variable's name.
  • What is written = the variable's value.
  • Rubbing out and writing again = changing the value.

In Go, every variable also has a type: the kind of value it can hold.

  • int holds whole numbers, like 92.
  • string holds text, like "Asha".
  • bool holds true or false.

You will learn all the types in Data Types.

What You Will Learn

In this lesson, you will learn:

  1. How to declare, initialize, assign and reassign variables.
  2. The three ways to declare variables: var, :=, and many at once.
  3. How to make constants with const, and number them with iota.
  4. The rules for naming things, and Go's keywords.
  5. How to ignore a value with the blank identifier _.

Working with Variables

Variable Declaration

Declaration = telling Go: "make a new box with this name and this type".

Declare a variable

package main

import "fmt"

func main() {
	var marks int
	fmt.Println(marks)
}
0
  • var is the keyword that makes a variable.
  • marks is the name. int is the type.
  • We gave no value, so Go put the zero value of int, which is 0.
  • You will learn zero values in Data Types.

Variable Initialization

Initialization = giving a variable its first value when you make it.

Declare and initialize

package main

import "fmt"

func main() {
	var name string = "Asha"
	var marks int = 92
	fmt.Println(name, marks)
}
Asha 92

Variable Assignment and Reassignment

Assignment = putting a value into a variable with =.

Reassignment = putting a new value into a variable that already has one.

  • The old value is gone.
  • The type cannot change: an int box only takes whole numbers.

Press Play and watch the box change.

Watch the value change

Watch two things:

  • Memory: the value in the box changes, but the name stays.
  • Output: each Println shows the value at that moment.

A Wrong Type Is Not Allowed

Run this. It puts text into an int box.

Wrong type

package main

import "fmt"

func main() {
	var marks int = 70
	marks = "eighty"
	fmt.Println(marks)
}
  • Go stops before running anything.
  • The real go tool says: cannot use "eighty" (untyped string constant) as int value in assignment.
  • Fix: keep the same type, like marks = 80.

Simple lesson: declare a box, give it a value, and change the value later, but never its type.

Variable Declaration Forms

Go has a few ways to make variables. Click each tab and compare.

Three ways to make a variable

The var Keyword

  • var name type = value is the full form.
  • You can leave out the type, or the value, but not both.
  • Use var when you want the zero value, like var count int.

Short Variable Declaration (:=)

:= = declare and initialize in one step, inside a function.

Short declaration

package main

import "fmt"

func main() {
	student := "Ravi"
	class := 8
	present := true
	fmt.Println(student, class, present)
}
Ravi 8 true
  • := makes a new variable.
  • = changes a variable that already exists.
  • At least one new name must be on the left of :=.

:= does not work outside a function.

At the top of a file, write var school = "Green Valley" instead.

Multiple Variable Declarations

You can make many variables in one line, or in a group.

Many variables at once

package main

import "fmt"

var (
	school = "Green Valley School"
	city   = "Pune"
)

func main() {
	var maths, science int = 91, 88
	name, class := "Meena", "8A"
	fmt.Println(school, city)
	fmt.Println(name, class, maths, science)
}
Green Valley School Pune
Meena 8A 91 88
  • var ( ... ) groups many variables neatly.
  • a, b := 1, 2 gives values in the same order: a gets 1, b gets 2.

Swapping Two Values

Go can assign many values at once. This makes swapping easy.

Swap two values

package main

import "fmt"

func main() {
	first, second := "Asha", "Ravi"
	first, second = second, first
	fmt.Println(first, second)
}
Ravi Asha
  • Go reads all the values on the right first.
  • Then it puts them into the boxes on the left.

Simple lesson: use := inside functions, and var outside them or when you want a zero value.

Constants

Constant = a named value that can never change.

Some school facts never change:

  • the number of days in a week: 7
  • the pass mark: 35
  • the school's name

The const Keyword

Make constants

package main

import "fmt"

const passMark = 35
const school = "Green Valley School"

func main() {
	const daysInWeek = 7
	fmt.Println(school, passMark, daysInWeek)
}
Green Valley School 35 7
  • const makes a constant.
  • A constant needs its value when you make it.
  • The value must be known before the program runs, like 35 or "text".

Now try to change one:

A constant cannot change

package main

import "fmt"

func main() {
	const passMark = 35
	passMark = 40
	fmt.Println(passMark)
}
  • Go stops: cannot assign to passMark.
  • That is the point of a constant: no one changes it by mistake.

Typed and Untyped Constants

Typed vs untyped constants

Untyped constant = a constant with no fixed type yet. Go gives it a type where you use it.

An untyped constant fits many types

package main

import "fmt"

const half = 0.5

func main() {
	var price float64 = 80
	var weight float32 = 3
	fmt.Println(price*half, weight*half)
}
40 1.5
  • half works with a float64 and a float32.
  • A typed constant const half float64 = 0.5 would fail with the float32.

iota

iota = a counter that Go uses inside a const ( ) group. It starts at 0 and goes up by 1 on each line.

It is great for numbering things, like the days of a timetable.

How iota counts

You can also do maths with iota:

iota with maths

package main

import "fmt"

const (
	_  = iota
	KB = 1 << (10 * iota)
	MB = 1 << (10 * iota)
)

func main() {
	fmt.Println(KB, MB)
}
1024 1048576
  • The first line uses _, so 0 is thrown away.
  • KB gets iota = 1, MB gets iota = 2.
  • << doubles a number many times. You will learn it in Operators.

Easy way to remember

  • var = a box whose value can change.
  • const = a box that is sealed forever.
  • iota = an automatic counter for a const group.

Simple lesson: use const for values that never change, and iota to number them for you.

Identifiers and Keywords

Identifier = a name you choose, for a variable, a constant or a function.

Naming Rules

  • Use letters, digits and _ only.
  • Start with a letter or _, never a digit.
  • No spaces, and no symbols like - or @.
  • Capital letters matter: marks and Marks are two different names.
  • Do not use a keyword as a name.
NameAllowed?Why
totalMarksYesLetters only.
class8AYesDigits are fine after the first letter.
_tempYesCan start with _.
8ANoStarts with a digit.
total-marksNo- is the minus sign.
funcNoIt is a keyword.

Naming Style

Go programmers use camelCase:

  • start small, then capital at each new word: studentName, totalMarks
  • short names for short jobs: i for a loop counter
  • clear names for long jobs: attendanceCount, not ac

Keywords

Keyword = a word Go keeps for itself. You cannot use it as a name.

Go has 25 keywords:

break     default      func     interface   select
case      defer        go       map         struct
chan      else         goto     package     switch
const     fallthrough  if       range       type
continue  for          import   return      var

Exported vs Unexported Identifiers

The first letter of a name decides who can see it:

  • Capital first letter (Total) = exported: other packages can use it.
  • Small first letter (total) = unexported: only this package can use it.
  • This is why we write fmt.Println, with a capital P.
  • You will learn this fully in Packages and Modules.

Simple lesson: names use letters, digits and _, start with a letter, and the first letter's case decides who can see them.

The Blank Identifier

Blank identifier = _, a name that means "throw this value away".

Unused Variables Are Not Allowed

Go does not allow a variable you never use. Run this.

An unused variable

package main

import "fmt"

func main() {
	name := "Asha"
	age := 13
	fmt.Println(name)
}
./prog.go:7:2: declared and not used: age
  • 7:2 means line 7, column 2.
  • Fix: use age, or delete it.
  • Go is strict here to keep code clean.

Ignoring Return Values

Some functions give back two values. If you need only one, put _ in place of the other.

Ignore a value with _

package main

import "fmt"

func main() {
	count, _ := fmt.Println("Hello")
	fmt.Println("Bytes printed:", count)
}
Hello
Bytes printed: 6
  • fmt.Println gives back two values: how many bytes it printed, and an error.
  • We keep the count and throw the error away with _.
  • Hello plus the new line is 6 bytes.

Ignoring Unused Values

You can also use _ to skip a value in a list:

Skip the middle value

package main

import "fmt"

func main() {
	name, _, city := "Kavya", 13, "Mysuru"
	fmt.Println(name, city)
}
Kavya Mysuru

Simple lesson: every variable must be used, and _ is how you say "I do not need this value".

TL;DR

  1. Variable = a named box whose value can change.

    • Declare: var marks int
    • Initialize: var marks int = 90
    • Short form inside functions: marks := 90
    • Reassign: marks = 95 (same type only)
  2. Constant = const passMark = 35. It never changes.

    • Untyped = no fixed type, fits where it is used.
    • iota = counter in a const ( ) group: 0, 1, 2, ...
  3. Identifier = a name: letters, digits, _, not starting with a digit.

    • Capital first letter = exported.
  4. Keyword = one of Go's 25 reserved words.
  5. Blank identifier = _, throws a value away.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
count := 5 at the top of a file:= works everywhere:= works only inside functionssyntax error: non-declaration statement outside function body
marks := 90 twice in one block:= can change a valueUse = to change an existing variableno new variables on left side of :=
marks = "ninety"A variable can change typeThe type is fixed forevercannot use "ninety" ... as int value
An unused variableExtra variables are harmlessEvery variable must be useddeclared and not used
Changing a constantconst is like varA constant never changescannot assign to passMark
total-marks := 10- can join wordsUse camelCase: totalMarksA syntax error.
Marks vs marksCase does not matterThey are two different namesundefined: marks

Check Yourself

Exercises

What to Remember

  • A variable is a named box. Its value can change, but its type cannot.
  • Inside functions, := is the short way to make a variable. Use = to change it.
  • const makes a value that never changes. iota numbers a const group.
  • Names use letters, digits and _. A capital first letter means exported.
  • Every variable and import must be used. Use _ to throw a value away.

Next: Data Types. You will learn the kinds of values Go can store, their zero values, and how to convert between them.