Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 1 | # Summary |
| 2 | |
swyman | 407ce0e | 2015-03-27 10:33:56 -0700 | [diff] [blame^] | 3 | Go's ` iota ` identifier is used in ` const ` declarations to simplify definitions of incrementing numbers. Because it can be used in expressions, it provides a generality beyond that of simple enumerations. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 4 | |
| 5 | The values of iota start at zero within each const block and increment by one each time it is seen. This can be combined with the constant shorthand (leaving out everything after the constant name) to very concisely define related constants. |
| 6 | |
| 7 | Iota: http://golang.org/doc/go_spec.html#Iota |
| 8 | |
| 9 | Constant declarations: http://golang.org/doc/go_spec.html#Constant_declarations |
| 10 | |
| 11 | # Examples |
| 12 | |
| 13 | The official spec has two great examples: |
| 14 | |
| 15 | http://golang.org/doc/go_spec.html#Iota |
| 16 | |
| 17 | Here's one from Effective Go: |
| 18 | |
| 19 | ``` |
| 20 | type ByteSize float64 |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 21 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 22 | const ( |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 23 | _ = iota // ignore first value by assigning to blank identifier |
| 24 | KB ByteSize = 1 << (10 * iota) |
| 25 | MB |
| 26 | GB |
| 27 | TB |
| 28 | PB |
| 29 | EB |
| 30 | ZB |
| 31 | YB |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 32 | ) |
| 33 | ``` |