V (programming language): Difference between revisions

Content deleted Content added
Jan200101 (talk | contribs)
Undid revision 1306725083 by 178.69.159.68 (talk), please discuss this on the talk page or Wikipedia:Copyright problems/2025 July 15 before reverting this
Jan200101 (talk | contribs)
Rewrite Structs and Heap structs examples from scratch with additional mention to initilization by name and by position as well as heap allocation via attribute.
Line 83:
 
=== Structs ===
{{Copyvio|timestamp=20250715164557 |url=https://docs.vlang.io/structs.html}}
Struct example:<ref name="Knott"/><ref name="section"/>
<syntaxhighlight lang="Vv">
struct PlaceFoobar {
a number int
name string
b int
score f32
}
 
// Struct fields can be initialized by name
mut p := Place {
var1 := Foobar {
a: 15
number: 21
b: 25
name: "baz"
score: 2.5
}
 
println(p.a) // A dot is used to access struct fields
// or by position
// Alternative literal syntax can be used
pvar2 := PlaceFoobar {1550, "qux", 253.14}
assert p.a == 15
</syntaxhighlight>
</div>
 
=== Heap structs ===
 
{{Copyvio|timestamp=20250715164557 |url=https://docs.vlang.io/structs.html#heap-structs}}
Structs that are allocatedreferenced onor have the stackheap byattribute default. The {{code|&}} prefix canwill be used, for getting a referenceallocated to itthe andheap allocatinginstead onof the heap insteadstack:{{sfn|Rao|2021}}
<syntaxhighlight lang="Vv">
struct PlaceFoo {
a number int
b int
}
 
@[heap]
p := &Place{30, 30}
struct Bar {
// References use the same syntax to access fields
number f32
println(p.a)
}
 
// Structs that are referenced are heap allocated
var1 := &Foo {2}
 
// Bar is always heap allocated because of its [heap] attribute
var2 := Bar{4.5}
 
</syntaxhighlight>
</div>
 
=== Methods ===