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

checker: disallow nil assignment on non pointer struct fields (#16056)

This commit is contained in:
Swastik Baranwal 2022-10-13 13:06:59 +05:30 committed by GitHub
parent fb3d093e01
commit 3e33f4a11d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 0 deletions

View File

@ -116,6 +116,12 @@ pub fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
}
continue
}
if field.default_expr is ast.UnsafeExpr {
if field.default_expr.expr is ast.Nil && !field.typ.is_ptr()
&& c.table.sym(field.typ).kind != .function && !field.typ.is_pointer() {
c.error('cannot assign `nil` to a non-pointer field', field.type_pos)
}
}
if field.default_expr is ast.IntegerLiteral {
if field.default_expr.val == '0' {
c.warn('unnecessary default value of `0`: struct fields are zeroed by default',

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.vv:4:7: error: cannot assign `nil` to a non-pointer field
2 |
3 | struct Foo {
4 | bar SomeInterface = unsafe{ nil }
| ~~~~~~~~~~~~~
5 | }
6 | fn main() {

View File

@ -0,0 +1,9 @@
interface SomeInterface{}
struct Foo {
bar SomeInterface = unsafe{ nil }
}
fn main() {
foo := Foo{}
dump(foo)
}