docs: document the `[required]` struct attribute (#6956)
parent
5ba5a53b77
commit
bbea7fb91f
15
doc/docs.md
15
doc/docs.md
|
@ -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' />
|
||||||
|
|
||||||
|
|
|
@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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{
|
||||||
|
|
Loading…
Reference in New Issue