fixed size array with const size: `numbers := [N]int`

pull/1461/head
Alexander Medvednikov 2019-08-04 03:59:12 +02:00
parent f306fbb2f0
commit 576192949d
2 changed files with 30 additions and 1 deletions

View File

@ -2482,7 +2482,16 @@ fn (p mut Parser) map_init() string {
fn (p mut Parser) array_init() string {
p.is_alloc = true
p.check(.lsbr)
is_integer := p.tok == .number
mut is_integer := p.tok == .number // for `[10]int`
// fixed length arrays with a const len: `nums := [N]int`, same as `[10]int` basically
mut is_const_len := false
if p.tok == .name {
c := p.table.find_const(p.prepend_pkg(p.lit))
if c.name != '' && c.typ == 'int' && p.peek() == .rsbr && !p.inside_const {
is_integer = true
is_const_len = true
}
}
lit := p.lit
mut typ := ''
new_arr_ph := p.cgen.add_placeholder()
@ -2504,6 +2513,9 @@ fn (p mut Parser) array_init() string {
if p.table.known_type(name) {
p.cgen.resetln('')
p.gen('STRUCT_DEFAULT_VALUE')
if is_const_len {
return '[${p.mod}__$lit]$name'
}
return '[$lit]$name'
}
else {

View File

@ -160,3 +160,20 @@ fn test_reverse() {
assert d[i] == b[b.len-i-1]
}
}
const (
N = 5
)
fn test_fixed() {
mut nums := [4]int
assert nums[0] == 0
assert nums[1] == 0
assert nums[2] == 0
assert nums[3] == 0
nums[1] = 7
assert nums[1] == 7
///////
nums2 := [N]int
assert nums2[N - 1] == 0
}