DEV Community

Cover image for Go language constants
toebes618
toebes618

Posted on

2

Go language constants

In Go programming, a constant is a simple constant value of the identifier, the program runs, the amount can not be modified.

Data type constant may be only boolean, numeric (integer, floating point and complex) and string.

Constant definition format:

    const identifier [type] = value

It can omit the type specifier [type], because the compiler can infer the type based on the value of the variable.

  • Explicit typing: const b string = "abc"

  • Implicit type definition: const b = "abc"

More of the same type of statement can be abbreviated as:

    const c_name1, c_name2 = value1, value2

The following examples demonstrate the application of constants:

package main

import "fmt"

func main () {
   const LENGTH int = 10
   const WIDTH int = 5
   var area int
   const a, b, c = 1, false, "str" // multiple assignment
   area = LENGTH * WIDTH
   fmt.Printf( "area:% d", area)
   println()
   println(a, b, c)
}

Examples of the above operating results are:

area: 50
1 false str

Constants can also be used to enumerate:

    const (
        Unknown = 0
        Female = 1
        Male = 2
    )

Numbers 0, 1 and 2, respectively, on behalf of unknown gender, women and men.

Constants can use len(), cap(), unsafe.Sizeof().

package main

import "unsafe"
const (
    a = "abc"
    b = len(a)
    c = unsafe.Sizeof(a)
)

func main() {
    println(a, b, c)
}

Examples of the above operating results are:

abc 3 16

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay