Learning Golang: Literals and Constants

Share on:

This is part 10 of my journey learning Golang.

Literals

In Go, values can be many things. Just to name a few, values can be numbers (like 109), or text wrapped in quotes (like “Hello world”).

Literals are values written in the source code. For example:

1fmt.Println("Hello, world!")       // String literal
2fmt.Println(42)                    // Integer literal
3fmt.Println(3.141592653589793238)  // Floating point literal

Constants

In addition to literal values (i.e. values directly expressed in the source code), Go also allows “named values”, i.e. values identified by a name. These named values are called “constants” because the value represented by the name remains the same throughout the runtime of the program.

Example:

 1package main
 2
 3import (
 4  "fmt"
 5)
 6
 7func main() {
 8  const inchesPerFeet = 12
 9  fmt.Println("There are", inchesPerFeet, "inches in a foot.")
10}

This program prints There are 12 inches in a foot.


comments powered by Disqus