1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix nested option struct init (fix #17415) (#17425)

This commit is contained in:
yuyi 2023-02-28 20:02:17 +08:00 committed by GitHub
parent ebeb652348
commit b9a8a21094
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 4 deletions

View File

@ -306,13 +306,28 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
fn (mut g Gen) zero_struct_field(field ast.StructField) bool { fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
sym := g.table.sym(field.typ) sym := g.table.sym(field.typ)
if sym.kind == .struct_ {
info := sym.info as ast.Struct
if info.fields.len == 0 {
return false
}
}
field_name := if sym.language == .v { c_name(field.name) } else { field.name } field_name := if sym.language == .v { c_name(field.name) } else { field.name }
if sym.info is ast.Struct {
if sym.info.fields.len == 0 {
return false
} else if !field.has_default_expr {
mut has_option_field := false
for fd in sym.info.fields {
if fd.typ.has_flag(.option) {
has_option_field = true
break
}
}
if has_option_field {
default_init := ast.StructInit{
typ: field.typ
}
g.write('.${field_name} = ')
g.struct_init(default_init)
return true
}
}
}
g.write('.${field_name} = ') g.write('.${field_name} = ')
if field.has_default_expr { if field.has_default_expr {
if sym.kind in [.sum_type, .interface_] { if sym.kind in [.sum_type, .interface_] {

View File

@ -0,0 +1,16 @@
struct Data {
a ?int
b ?int = 1
}
struct Data2 {
d Data
}
fn test_nested_option_struct_init() {
d2 := Data2{}
println(d2)
assert d2.d.a == none
assert d2.d.b != none
assert d2.d.b? == 1
}