docs: document the `[required]` struct attribute (#6956)

pull/6980/head
spaceface777 2020-11-27 14:37:12 +01:00 committed by GitHub
parent 5ba5a53b77
commit bbea7fb91f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 2 deletions

View File

@ -1139,6 +1139,21 @@ Array and map fields are allocated.
It's also possible to define custom default values. It's also possible to define custom default values.
### Required fields
```v
struct Foo {
n int [required]
}
```
You can mark a struct field with the `[required]` attribute, to tell V that
that field must be initialized when creating an instance of that struct.
This example will not compile, since the field `n` isn't explicitly initialized:
```v failcompile
_ = Foo{}
```
<a id='short-struct-initialization-syntax' /> <a id='short-struct-initialization-syntax' />

View File

@ -589,7 +589,7 @@ pub fn (mut c Checker) struct_init(mut struct_init ast.StructInit) table.Type {
} }
} }
if !found { if !found {
c.error('field `${type_sym.source_name}.$field.name` is required', c.error('field `${type_sym.source_name}.$field.name` must be initialized',
struct_init.pos) struct_init.pos)
} }
} }

View File

@ -1,4 +1,4 @@
vlib/v/checker/tests/struct_required_field.vv:12:6: error: field `Abc.f3` is required vlib/v/checker/tests/struct_required_field.vv:12:6: error: field `Abc.f3` must be initialized
10 | f3: 789 10 | f3: 789
11 | } 11 | }
12 | _ = Abc{ 12 | _ = Abc{