cgen: fix struct field option type with default value init (#19420)

This commit is contained in:
yuyi 2023-09-23 20:54:08 +08:00 committed by GitHub
parent 04d28f2a74
commit 83d461441e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 2 deletions

View File

@ -359,8 +359,7 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
if field.has_default_expr { if field.has_default_expr {
if sym.kind in [.sum_type, .interface_] { if sym.kind in [.sum_type, .interface_] {
if field.typ.has_flag(.option) { if field.typ.has_flag(.option) {
g.expr_opt_with_cast(field.default_expr, field.default_expr_typ.set_flag(.option), g.expr_with_opt(field.default_expr, field.default_expr_typ, field.typ)
field.typ)
} else { } else {
g.expr_with_cast(field.default_expr, field.default_expr_typ, field.typ) g.expr_with_cast(field.default_expr, field.default_expr_typ, field.typ)
} }

View File

@ -0,0 +1,13 @@
type SomeType = SomeStruct | string
struct SomeStruct {}
struct AnotherStruct {
field ?SomeType = 'default_string'
}
fn test_struct_field_option_type_with_default_value() {
s := AnotherStruct{}
println(s.field)
assert '${s.field}' == "Option(SomeType('default_string'))"
}