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

cgen: fix none initialization to struct member (#18295)

This commit is contained in:
Felipe Pena 2023-05-29 09:35:41 -03:00 committed by GitHub
parent ae8e9af11f
commit 05b832a317
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 1 deletions

View File

@ -163,6 +163,10 @@ fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
field.default_expr.pos)
}
}
if field.typ.has_flag(.option) && field.default_expr is ast.None {
c.warn('unnecessary default value of `none`: struct fields are zeroed by default',
field.default_expr.pos)
}
continue
}
if field.typ in ast.unsigned_integer_type_idxs {

View File

@ -346,7 +346,11 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
return true
}
if field.typ.has_flag(.option) {
if field.default_expr is ast.None {
tmp_var := g.new_tmp_var()
g.expr_with_tmp_var(ast.None{}, ast.none_type, field.typ, tmp_var)
return true
} else if field.typ.has_flag(.option) {
tmp_var := g.new_tmp_var()
g.expr_with_tmp_var(field.default_expr, field.default_expr_typ, field.typ,
tmp_var)

View File

@ -0,0 +1,20 @@
struct Node[T] {
mut:
value T
next ?&Node[T] = none
}
fn test_main() {
mut n := Node[int]{
value: 1
}
mut m := Node[int]{
value: 2
}
n.next = &m
a := n.next or { return }
dump(a)
dump(m)
dump(n)
assert a.value == 2
}