0
0
Goprogramming~5 mins

Constants in Go

Choose your learning style9 modes available
Introduction

Constants hold values that do not change while the program runs. They help keep important values safe and easy to use.

When you have a value like Pi that never changes.
To name fixed settings like maximum number of users.
To avoid repeating the same number or text in many places.
When you want to make your code easier to read with meaningful names.
Syntax
Go
const name type = value

You can omit the type if Go can guess it from the value.

Constants must be assigned a value when declared and cannot change later.

Examples
Defines a constant named Pi with type float64 and value 3.14.
Go
const Pi float64 = 3.14
Defines a string constant Greeting without specifying type explicitly.
Go
const Greeting = "Hello"
Defines multiple constants together using parentheses.
Go
const (
  MaxUsers = 100
  Version = 1.0
)
Sample Program

This program uses constants Pi and Greeting to print fixed messages. The values do not change anywhere in the program.

Go
package main

import "fmt"

const Pi = 3.14159
const Greeting = "Welcome to Go!"

func main() {
    fmt.Println(Greeting)
    fmt.Println("Pi is approximately", Pi)
}
OutputSuccess
Important Notes

Constants can be numbers, strings, or booleans.

You cannot use variables to set constant values.

Constants help prevent accidental changes to important values.

Summary

Constants store fixed values that do not change.

They make code safer and easier to understand.

Use const keyword to declare constants in Go.