mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
ast, checker, cgen: fix array of sumtype initialisation with a default init:
(#13178)
This commit is contained in:
parent
7fe62a8b3e
commit
dfc23d939f
@ -1166,9 +1166,10 @@ pub:
|
||||
has_default bool
|
||||
has_it bool // true if temp variable it is used
|
||||
pub mut:
|
||||
expr_types []Type // [Dog, Cat] // also used for interface_types
|
||||
elem_type Type // element type
|
||||
typ Type // array type
|
||||
expr_types []Type // [Dog, Cat] // also used for interface_types
|
||||
elem_type Type // element type
|
||||
default_type Type // default value type
|
||||
typ Type // array type
|
||||
}
|
||||
|
||||
pub struct ArrayDecompose {
|
||||
|
@ -20,6 +20,7 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
|
||||
if node.has_default {
|
||||
default_expr := node.default_expr
|
||||
default_typ := c.check_expr_opt_call(default_expr, c.expr(default_expr))
|
||||
node.default_type = default_typ
|
||||
c.check_expected(default_typ, node.elem_type) or {
|
||||
c.error(err.msg, default_expr.position())
|
||||
}
|
||||
|
@ -213,7 +213,7 @@ fn (mut g Gen) array_init(node ast.ArrayInit) {
|
||||
g.write('}[0])')
|
||||
} else if node.has_default {
|
||||
g.write('&($elem_styp[]){')
|
||||
g.expr(node.default_expr)
|
||||
g.expr_with_cast(node.default_expr, node.default_type, node.elem_type)
|
||||
g.write('})')
|
||||
} else if node.has_len && node.elem_type == ast.string_type {
|
||||
g.write('&($elem_styp[]){')
|
||||
|
11
vlib/v/tests/array_of_sumtype_with_default_test.v
Normal file
11
vlib/v/tests/array_of_sumtype_with_default_test.v
Normal file
@ -0,0 +1,11 @@
|
||||
type Abc = int | string
|
||||
|
||||
fn test_array_of_sumtype_with_default() {
|
||||
a1 := []Abc{len: 1, init: 22}
|
||||
println(a1)
|
||||
assert '$a1' == '[Abc(22)]'
|
||||
|
||||
a2 := []Abc{len: 1, init: 'hello'}
|
||||
println(a2)
|
||||
assert '$a2' == "[Abc('hello')]"
|
||||
}
|
Loading…
Reference in New Issue
Block a user