From 1e76cccd48e15640165023ca248a89fb5b4ae507 Mon Sep 17 00:00:00 2001 From: kahsa Date: Thu, 3 Mar 2022 20:20:49 +0900 Subject: [PATCH] doc: add a struct reference example (#13638) --- doc/docs.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 384a9a8542..2a46ccff0e 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1929,6 +1929,32 @@ println(p.x) The type of `p` is `&Point`. It's a [reference](#references) to `Point`. References are similar to Go pointers and C++ references. +```v +struct Foo { +mut: + x int +} + +fa := Foo{1} +mut a := fa +a.x = 2 +assert fa.x == 1 +assert a.x == 2 + +// fb := Foo{ 1 } +// mut b := &fb // error: `fb` is immutable, cannot have a mutable reference to it +// b.x = 2 + +mut fc := Foo{1} +mut c := &fc +c.x = 2 +assert fc.x == 2 +assert c.x == 2 +println(fc) // Foo{ x: 2 } +println(c) // &Foo{ x: 2 } // Note `&` prefixed. +``` +see also [Stack and Heap](#stack-and-heap) + ### Default field values ```v