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:
nameholds"Asha"marksholds92passedholdstrue
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.
intholds whole numbers, like92.stringholds text, like"Asha".boolholdstrueorfalse.
You will learn all the types in Data Types.
What You Will Learn
In this lesson, you will learn:
- How to declare, initialize, assign and reassign variables.
- The three ways to declare variables:
var,:=, and many at once. - How to make constants with
const, and number them withiota. - The rules for naming things, and Go's keywords.
- 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
varis the keyword that makes a variable.marksis the name.intis the type.- We gave no value, so Go put the zero value of
int, which is0. - 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
intbox 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
Printlnshows 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
gotool 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 = valueis the full form.- You can leave out the type, or the value, but not both.
- Use
varwhen you want the zero value, likevar 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, 2gives values in the same order:agets1,bgets2.
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
constmakes a constant.- A constant needs its value when you make it.
- The value must be known before the program runs, like
35or"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
halfworks with afloat64and afloat32.- A typed constant
const half float64 = 0.5would fail with thefloat32.
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
_, so0is thrown away. KBgetsiota = 1,MBgetsiota = 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 aconstgroup.
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:
marksandMarksare two different names. - Do not use a keyword as a name.
| Name | Allowed? | Why |
|---|---|---|
totalMarks | Yes | Letters only. |
class8A | Yes | Digits are fine after the first letter. |
_temp | Yes | Can start with _. |
8A | No | Starts with a digit. |
total-marks | No | - is the minus sign. |
func | No | It is a keyword. |
Naming Style
Go programmers use camelCase:
- start small, then capital at each new word:
studentName,totalMarks - short names for short jobs:
ifor a loop counter - clear names for long jobs:
attendanceCount, notac
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 capitalP. - 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:2means 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.Printlngives back two values: how many bytes it printed, and an error.- We keep the count and throw the error away with
_. Helloplus 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
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)
- Declare:
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, ...
Identifier = a name: letters, digits,
_, not starting with a digit.- Capital first letter = exported.
- Keyword = one of Go's 25 reserved words.
- Blank identifier =
_, throws a value away.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
count := 5 at the top of a file | := works everywhere | := works only inside functions | syntax error: non-declaration statement outside function body |
marks := 90 twice in one block | := can change a value | Use = to change an existing variable | no new variables on left side of := |
marks = "ninety" | A variable can change type | The type is fixed forever | cannot use "ninety" ... as int value |
| An unused variable | Extra variables are harmless | Every variable must be used | declared and not used |
| Changing a constant | const is like var | A constant never changes | cannot assign to passMark |
total-marks := 10 | - can join words | Use camelCase: totalMarks | A syntax error. |
Marks vs marks | Case does not matter | They are two different names | undefined: 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. constmakes a value that never changes.iotanumbers aconstgroup.- 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.