Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
const
constant

How to declare constants in Go

Educative Answers Team

Constants are used to represent fixed values; their values cannot be changed at a later stage in the program. Any attempt to change the value of a constant will cause a runtime panic.

Syntax

To declare a constant and give it a name, the const keyword is used.

svg viewer
const myValue = "Hello World"
const country, code = "Pakistan", 92

Constants cannot be declared using the := syntax.

Code

The following code shows how to declare constant values in our code:

package main
import "fmt"

const Pi = 3.14

func main() {
	const name = "John"
	fmt.Println("Hello", name)
	fmt.Println("Value of Pi is", Pi)

	const myval = true
	fmt.Println("Variable myval contains:", myval)
}

Typed constants

In Golang, constants are typed when you explicitly specify the type in the declaration:

const my_typed_const int = 20 

With typed constants, all the flexibility that comes with untyped constants (like assigning them to any variable of compatible type or mixing them in mathematical operations) is lost.

Untyped Constants

In Golang, all constants are untyped unless they are explicitly given a type at declaration.

const my_untyped_const = 20 

Untyped constants allow for flexibility. They can be assigned to any variable of compatible type or mixed into​ mathematical operations.


RELATED TAGS

golang
go
const
constant
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring