Variables and Constants

Variables

There are two ways to declare a variable in Golang

  1. Use var keyword
  2. Use := sign

Using var keyword

var statement declares a list of variables and it can have type at the last.

var statement can be at a package level or at a function level.

Either type or value is mandate when declaring a variable using var.

Variables can incur the type of the value, if the type is not explicitly specified.

Variables declared without values will get initialized with zero value of the type.

When type is not specified, multiple values of different types can be initialized in a single var statement.

Syntax

var name1[, name2, name3, ...] type = value1[, value2, value3, ...]
var name1[, name2, name3] type
var name = value

Example

var bookCount, authorCount int = 10, 2
var firstName, lastName string
var name, age = "Sheldon", 25
var name = "Sheldon" 

Using := sign

Variables declared with := sign, often called as short assignment statement, can be used within functions.
type cannot be explicitly mentioned with this kind of declaration.

Syntax

name1[, name2, ...] := value1[, value2, ...]

Example

bookCount, authorCount := 10, 2
name, age := "Sheldon", 25
name := "Sheldon"

Constants

Constants are declared just like variables, but with const keyword.
Constants cannot be declared using short assignment operations (:=).
Unlike variables, constants must have a value irrespective whether type is provided or not.

Syntax

const name1[, name2, ...] = value1[, value2, ...]
const name type = value

Example

const title, year = "The Big Bang Theory", 2007
const PI = 3.14

Comments