Skip to content

Commit 130f35c

Browse files
authored
checker: fix embedded struct field with default value (#17777)
1 parent 34f5f05 commit 130f35c

2 files changed

Lines changed: 42 additions & 7 deletions

File tree

vlib/v/checker/struct.v

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -118,17 +118,15 @@ fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
118118

119119
if field.has_default_expr {
120120
c.expected_type = field.typ
121-
default_expr_type := c.expr(field.default_expr)
122121
if !field.typ.has_flag(.option) && !field.typ.has_flag(.result) {
123-
c.check_expr_opt_call(field.default_expr, default_expr_type)
122+
c.check_expr_opt_call(field.default_expr, field.default_expr_typ)
124123
}
125-
struct_sym.info.fields[i].default_expr_typ = default_expr_type
126124
interface_implemented := sym.kind == .interface_
127-
&& c.type_implements(default_expr_type, field.typ, field.pos)
128-
c.check_expected(default_expr_type, field.typ) or {
125+
&& c.type_implements(field.default_expr_typ, field.typ, field.pos)
126+
c.check_expected(field.default_expr_typ, field.typ) or {
129127
if sym.kind == .interface_ && interface_implemented {
130-
if !c.inside_unsafe && !default_expr_type.is_real_pointer() {
131-
if c.table.sym(default_expr_type).kind != .interface_ {
128+
if !c.inside_unsafe && !field.default_expr_typ.is_real_pointer() {
129+
if c.table.sym(field.default_expr_typ).kind != .interface_ {
132130
c.mark_as_referenced(mut &node.fields[i].default_expr,
133131
true)
134132
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
struct Papa {
2+
fam_name string
3+
}
4+
5+
pub struct Child {
6+
Papa
7+
pub mut:
8+
activity Activity = Fun.roll
9+
age u8 = 2
10+
}
11+
12+
type Activity = Fun | Other
13+
14+
pub enum Fun {
15+
run
16+
roll
17+
jump
18+
}
19+
20+
pub struct Other {}
21+
22+
// Same struct without embedding just works.
23+
pub struct Human {
24+
fam_name string
25+
pub mut:
26+
activity Activity = Fun.roll
27+
age u8 = 2
28+
}
29+
30+
fn test_embed_struct_field_default_value() {
31+
c := Child{}
32+
println(c.activity)
33+
assert c.activity == Activity(Fun.roll)
34+
h := Human{}
35+
println(h.activity)
36+
assert h.activity == Activity(Fun.roll)
37+
}

0 commit comments

Comments
 (0)