Given a set of code like this, what is the output?
package main
func main() {
ary = [...]int{
'a': 1,
'b': 2,
'c': 3,
}
ary['a'] = 100
println(len(ary))
}
To make things easier, I’ll just give you four choices.
A. 3 B. 2 C. 100 D. Compilation error
And surprise! The answer is C.
This question is all about the rune
type and array
declaration in go.
In golang documentation, you can find the rune
type here.
Which says that rune
is an alias for int32
, and
A rune literal represents a rune constant, an integer value that represents a Unicode code point. A rune literal is expressed as one or more characters enclosed in single quotes, as in ‘x’ or ‘\n’.
When we give the compiler a simple ‘a’, it will treat the ‘a’ as a unsigned rune
constant.
And unsigned instants serving as the index of an array, will be given type int
.
Here is a simple example:
const r = 'a' // ok
var a int = r // ok
const r rune = 'a' // ok
var a int = r // cannot use r as type int in assignment
We know that 'a'
in ascii is 97, and rune
is an alias for int32
, so the compiler will treat 'a'
as a int32
constant, with value 97.
So the code at the beginning will be same as:
package main
func main() {
ary = [...]int{
97: 1,
98: 2,
99: 3,
}
ary[97] = 100
println(len(ary))
}
Obviously, the answer is C.100.