×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Can constants be modified in Go language?

Here, we will learn about the constants in the Go language, and check whether we can change the value of constant or not in Golang?
Submitted by IncludeHelp, on October 03, 2021

In Golang, the constants are declared like variables, but with the const keyword and the constant value. The constants can be of any type and they cannot be declared using the short variable declaration (:=).

Syntax to declare a constant:

const constat_name type = value 

Coming to the question, can constants be modified?

The answer is - No, the constants cannot be modified at runtime, they can be modified at compile-time only (i.e., while constant declaration).

Example:

package main

import (
	"fmt"
)

func main() {
	const x int = 100
	fmt.Println(x) // Prints 100

	// Error: cannot assign to x (declared const)
	x = 200
	fmt.Println(x)
}

Output:

./prog.go:12:4: cannot assign to x (declared const)

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.