2014年8月14日

Golang - constant and iota

In Go, declaring constants can be written like this:
const E = 2.71828



It's called untyped constant. You could specify a type for a const called typed constant.

const LUCKY int = 7

The different between untyped constant and typed constant is an untyped constant could be transfer proper type when be assigned to a variable, but typed constant wouldn't.

for example:

const A  = "yo" //untyped constant
const B string = "hi" //typed constant

type MS string

var c MS = A // valid
var d MS = B // invalid


Declaring many constants could use parenthesis for simplify:

const (
  I = 1
  J = 2
  K = 3
)

If the constants have same value, it's valid that assign value only to first constant.

const (
  I = 1
  J
  K
)

I, J and K would be 1.

When the constants are ascending, it's time to use the keyword "iota", the Go wiki says:
iota identifier is used in in const declarations to simplify definitions of incrementing numbers
Here's the example:

const (
  A = iota
  B
  C
)

A, B and C will be 0, 1, 2.

If the constants series are increase by 2 or more, we could declare the the different at the second constant

const (
  A = iota
  B = 9*iota // must multiple iota
  C
)

A, B and C will be 0, 9 18

沒有留言:

張貼留言