Constants in Go

 Constants are declared are as follows

package main

import "fmt"

func main() {
    const soundSpeed = 343
    fmt.Println(soundSpeed)
}

Some key points

A value should be assigned to a constant when it is declared

We cannot declare a constant and initialize it later.

Once a constant is created you cannot re-assign a value to that constant.

You cannot assign a value of a constant as a return value of a function, since the value of a constant is evaluated at compile time and methods are evaluated at runtime.

Implicit declaration syntax

Here the compiler will interpret the type as it runs to it

package main

import "fmt"

func main() {
    const soundSpeed = 343
    fmt.Println(soundSpeed)
    fmt.Println(soundSpeed + 3.65)
}

Output:




The following is an example for explicit declaration

package main

import "fmt"

func main() {
    const soundSpeed int = 343
    fmt.Println(soundSpeed)
    fmt.Println(soundSpeed + 3.65)
}

This will throw .\main.go:8:25: constant 3.65 truncated to integer error












No comments:

 My Attempt to learn AI  GPT Generative Pretrained Transformer Created by Google in 2017 with the publication of the paper "Attention ...

Popular in last 30 days