From 06bcd404b027a76924075520aa7a3f1e5e14b74c Mon Sep 17 00:00:00 2001 From: LilEnvy <75917200+lilenvy@users.noreply.github.com> Date: Fri, 8 Jan 2021 03:46:01 -0800 Subject: [PATCH] docs: add a note on initializing structs with reference fields (#7913) --- doc/docs.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index c4b5deadf8..2e531a2b8c 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -2737,6 +2737,42 @@ surrounding code). * Note: This is work in progress. +### Structs with reference fields + +Structs with references require explicitly setting the initial value to a +reference value unless the struct already defines its own initial value. + +Zero-value references, or nil pointers, will **NOT** be supported in the future, +for now data structures such as Linked Lists or Binary Trees that rely on reference +fields that can use the value `0`, understanding that it is unsafe, and that it can +cause a panic. + +```v +struct Node { + a &Node + b &Node = 0 // Auto-initialized to nil, use with caution! +} + +// Reference fields must be initialized unless an initial value is declared. +// Zero (0) is OK but use with caution, it's a nil pointer. +foo := Node{ + a: 0 +} +bar := Node{ + a: &foo +} +baz := Node{ + a: 0 + b: 0 +} +qux := Node{ + a: &foo + b: &bar +} +println(baz) +println(qux) +``` + ## Calling C functions from V ```v