Go Constants
- In Go, if a variable needs to hold a fixed value that cannot be changed, you should use the const keyword.
- The const keyword is used to declare a constant, meaning its value is immutable and cannot be modified after declaration.
Syntax:
const CONSTNAME type = value
Note: A constant must be assigned a value at the time of declaration.
Declaring a Constant
- To define a fixed value that doesn't change, you can declare a constant using the const keyword.
Example:
package main
import "fmt"
const PI = 3.14
func main() {
fmt.Println(PI)
}
- In this example, PI is declared as a constant with a value of 3.14. Once declared, its value cannot be modified.
Constant Rules
- Naming Rules: Constant names follow the same rules as variable names.
- Naming Convention: Constants are typically written in uppercase letters to distinguish them easily from variables.
- Scope: Constants can be declared both inside and outside of functions.
- Type Assignment: Constants can have a specified type or use type inference, depending on how they are declared.
Types of Constants
In Go, constants are categorized into two types:
1.Typed Constants
- These constants have an explicitly defined type. Once declared, they can only be used in contexts that match their type.
2.Untyped Constants
- These constants do not have a specific type when declared. Instead, they assume the type required by the context in which they are used.
Example:
package mainimport "fmt"
// Declare a typed constant of type int
const A int = 1
func main() {
fmt.Println(A)
}
Untyped Constants
- Untyped constants are constants that are declared without explicitly specifying a type. The type is determined based on how the constant is used.
Example:
package main
import "fmt"
const A = 1 // A is an untyped constant
func main() {
fmt.Println(A)
}
- In this example, A is an untyped constant. Its type will be inferred by the compiler based on the context in which it's used.
Note: In this case, the type of the constant is automatically determined by the compiler based on the assigned value.
Constants: Immutable and Read-Only
- In Go, once a constant is declared, its value cannot be changed. Constants are fixed values that are set at compile time and are read-only.
Example
package main
import ("fmt")
func main() {
const A = 1
A = 2 // This will cause a compile-time error
fmt.Println(A)
}
Output:
./prog.go:8:7: cannot assign to A
Explanation:
- The line A = 2 attempts to change the value of a constant, which is not allowed. Constants must remain unchanged throughout the program.
Declaring Multiple Constants in Go
- In Go, you can group multiple constants into a single block using parentheses. This improves code readability and organization.
Example:
package main
import "fmt"
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A)
fmt.Println(B)
fmt.Println(C)
}