Using Constants

· 105 words · 1 minute read

Using constants can often be more efficient than using variables where possible because any references to the constant will be replaced at compile time, where as a variable would have memory allocated to it and can be changed. Using a defined constant is very similar to using a variable and can be declared as a block outside of a function (usually at the top of a file) - a little like your import.

package main

import "fmt"

const (
    MESSAGE = "Hello Readers"
    URL     = "http://golangcode.com"
)

func main() {
    // Will output "Hello Readers of http://golangcode.com"
    fmt.Println(MESSAGE + " of " + URL)
}
Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!