doc: add a struct reference example (#13638)

pull/13643/head
kahsa 2022-03-03 20:20:49 +09:00 committed by GitHub
parent ac1b31dbba
commit 1e76cccd48
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 26 additions and 0 deletions

View File

@ -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