From bbea7fb91fbb1174ae2c5144f758a89d5c854e2c Mon Sep 17 00:00:00 2001 From: spaceface777 Date: Fri, 27 Nov 2020 14:37:12 +0100 Subject: [PATCH] docs: document the `[required]` struct attribute (#6956) --- doc/docs.md | 15 +++++++++++++++ vlib/v/checker/checker.v | 2 +- vlib/v/checker/tests/struct_required_field.out | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/doc/docs.md b/doc/docs.md index 67bd0ca08e..3b34cdc7ee 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1139,6 +1139,21 @@ Array and map fields are allocated. 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{} +``` diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 95a8729ead..8111c287e9 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -589,7 +589,7 @@ pub fn (mut c Checker) struct_init(mut struct_init ast.StructInit) table.Type { } } 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) } } diff --git a/vlib/v/checker/tests/struct_required_field.out b/vlib/v/checker/tests/struct_required_field.out index 6294ee4b61..212ca63189 100644 --- a/vlib/v/checker/tests/struct_required_field.out +++ b/vlib/v/checker/tests/struct_required_field.out @@ -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 11 | } 12 | _ = Abc{