Constants

Go doesn't have immutability for its variables, but defines another type of immutable value called constant. This is defined by the const keyword (instead of var), and they are values that cannot change. These values can be base types and custom types, which are as follows:

  • Numeric (integer, float)
  • Complex
  • String
  • Boolean

The value that's specified doesn't have a type when it's assigned to a variable. There's an automatic conversion of both numeric types and string-based types, as shown in the following code:

const PiApprox = 3.14

var PiInt int = PiApprox // 3, converted to integer
var Pi float64 = PiApprox // is a float

type MyString string

const Greeting = "Hello!"

var s1 string = Greeting // is a string
var s2 MyString = Greeting // string is converted to MyString

Numerical constants are very useful for mathematical operations because they are just regular numbers, so they can be used with any numerical variable type.