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.


package main

import (

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

type myStrType string

func main() {

    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


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


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