Skip to main content

Variables and Constants in Go

Welcome to our new tutorial on Variables and Constants in Go. Go has a strong and static type system. All variables and constants need to be declared before they can be used. This tutorial will guide you to understand the concepts of Variables and Constants in Go in an easy, thorough, and progressive manner.

Variables

In Go, a variable is simply a storage location, containing our data value. The value of a variable can be changed throughout the program. Go has support for variable types like integer types, floating-point numbers, complex numbers, boolean types, string types and more.

Declaration of Variables

In Go, variables are declared before they are used. The basic syntax of declaring variables in Go is as follows:

var variableName variableType

For example, to declare a variable named 'x' of type 'int' you would do:

var x int

You can also declare multiple variables at once:

var x, y, z int

Initialization of Variables

You can declare a variable and assign a value to it at the same time. This is called initialization.

var x int = 10

Go will automatically infer the type of the initialized variable.

var y = 10 // y is inferred as integer

Go also has a shorthand for declaring and initializing a variable in one line, using :=

z := 10

Constants

Constants are similar to variables, but the value of constants remains the same throughout the program. Once a constant is declared, it can not be changed.

Declaration of Constants

Constants are declared like variables, but with the 'const' keyword.

const constantName constantType = value

For example, to declare a constant named 'x' of type 'int' you would do:

const x int = 10

You can also declare multiple constants at once:

const x, y, z int = 10, 20, 30

Go will automatically infer the type of the initialized constant.

const y = 10 // y is inferred as integer

Conclusion

Variables and constants are fundamental concepts in any programming language, and Go is no different. Understanding these concepts will help you to build a strong foundation in Go. In the next tutorial, we will cover more about data types in Go. Keep practicing and happy coding!