Go Variables and Constants
In Go (also known as Golang), variables and constants are fundamental concepts used for storing and managing data within programs.
Variables in Go represent storage locations that hold values of a specific type, such as integers, strings, or custom-defined types. They are declared using the var
keyword and can be assigned values that can change during program execution. Go supports various types of variables, including basic types like int, float64, string, as well as composite types like arrays, slices, structs, and pointers.
Constants, on the other hand, are values that are and fix at compile time and cannot be change during program execution. They are declared using the const
keyword and provide a way to define named values that remain constant throughout the program’s lifecycle. Constants are typically use for defining configuration values, mathematical constants, or other immutable data.
Understanding variables and constants in Go is essential for writing clear, maintainable, and efficient code. By using variables and constants effectively, developers can manage data efficiently and ensure the correctness and stability of their Go programs.
A Variable in which a value cannot be change.
The ‘const’ keyword declares the variable as “constant”. That means it is unchangeable and read-only.
Syntax:
Const CONSTNAME type = value
Package main Import “fmt” Const PI=3.14 Func main() { Fmt.Println(PI) }
- Typed constants
Simple variable deceleration Go Lang program.
package main import "fmt" const X int = 10 func main() { fmt.Println(X) }
Output :
PS C:\GO_Language\constant> go run const1.go Value of X : 10
2.Untyped constants
Program to illustrate untyped variables.
package main import "fmt" const X = 11 //untyped constants/without a type func main() { fmt.Println(X) }
Output :
PS C:\GO_Language\constant> go run const2.go Value of X : 11
3.Program to illustrate mixed Constants.
package main import "fmt" const ( X int = 1 Y = 3343.4 Z = "Prwatech" ) func main() { fmt.Println(X) fmt.Println(Y) fmt.Println(Z) }
Output :
PS C:\GO_Language\constant> go run const3.go Integer Value : 1 Float Value : 3343.4 String Value : Prwatech