create an immutable variable in go

In Go, we can declare an immutable variable using the const keyword. Once a constant is defined, its value cannot be changed during runtime.

Here's an example:

main.go
package main

import "fmt"

func main() {
    const age int = 35
    fmt.Println("My age is", age)

    // This line will result in a compile-time error
    // age = 36
}
171 chars
12 lines

In the example above, we declare an integer constant named age with a value of 35. We then print the value of age to the console. If we try to reassign a value to age, we will receive a compile-time error.

Note that we can also declare multiple constants in a single line, like this:

main.go
const (
    name string = "John Doe"
    age int = 35
)
56 chars
5 lines

related categories

gistlibby LogSnag