programming

Untyped Constants in Golang

Golang is extremely explicit with types. It supports constants of a type. But how about a const 2 or hello. What type would they assume!?
Go solved this problem with untyped constants. Untyped means:

  1. A constant’s type depends on the type of assignee variable.
  2. The assignee’s type must have compatibility to hold constant’s value.

Example

package main

import (
    "fmt"
)

const (
    myconst      = `a untyped constant`
    anotherConst = "a typed const"
)

type myStrType string

func main() {
    fmt.Println("vim-go")

    var name string
    var number int

    // Since name is of type string, both untype & typed string
    // constants work fine.
    name = myconst
    name = anotherConst

    // Doesn't work because a untyped string still is a string.
    // We can't assign it to an integer.
    // number = myconst

    fmt.Println(name, number)

    // This is the use case of untyped consts.
    // A compatible type can hold an untyped constant.
    var newStr myStrType // <---------
    newStr = myconst
    fmt.Println(newStr)
}

Output

$ go run untyped_consts.go                                                                                                                                                                                                              vim-go
a typed const 0
a untyped constant

Remember

  • An untyped constant still has the type.
  • Only a typedef of original type can hold a untyped constant.

References

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.