forked from vlang/website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docs.html
1610 lines (1191 loc) · 37 KB
/
docs.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@t header
<script src="/js/jquery.min.js"></script>
<script>
$(document).ready(function() { $("a:contains(Documentation)").css('font-weight', '500') })
</script>
<style>
h2 {
border-top: 1px solid #dfdfdf;
padding-top: 10px;
}
code {
font-family: 'Roboto Mono';
background-color: #f0f0f0;
padding: 1px 3px 1px 3px;
}
</style>
<script>
$(document).ready(function() {
$('.run').click(function() {
var pre = $(this).prev('pre')
localStorage.setItem('play', pre.text())
window.open('/play')
});
});
</script>
<div class='sep' style='padding:0'></div>
<div class='center'>
<div class='toc'>
<a href='#introduction'>%introduction</a>
<a href='#hello'>Hello World</a>
<a href='#comments'>%comments</a>
<a href='#fns'>%functions</a>
<a href='#vars'>%variables</a>
<a href='#btypes'>%basic_types</a>
<a href='#strings'>%strings</a>
<a href='#arrays'>%arrays</a>
<a href='#maps'>%maps</a>
<a href='#if'>If</a>
<a href='#in'>%in_op</a>
<a href='#for'>%for_loop</a>
<a href='#switch'>%switch</a>
<a href='#structs'>%structs</a>
<a href='#mod'>%access_mod</a>
<a href='#methods'>%methods</a>
<a href='#recvs'>%pure_fns</a>
<a href='#highfns'>%high_fns</a>
<a href='#consts'>%constants</a>
<a href='#modules'>%modules</a>
<a href='#interfaces'>%interfaces</a>
<a href='#enums'>%enums</a>
<a href='#option'>%optionals_and_errors</a>
<a href='#generics'>%generics</a>
<a href='#concurrency'>%concurrency</a>
<a href='#json'>%decoding_json</a>
<a href='#testing'>%testing</a>
<a href='#memory'>%memory_management</a>
<a href='#defer'>Defer</a>
<a href='#vfmt'>vfmt</a>
<br>
Advanced Topics
<br>
<br>
<a href='#calling_c'>Calling C functions from V</a>
<a href='#comp_if'>Compile time if</a>
<a href='#codegen'>Reflection via codegen</a>
<a href='#op'>Limited operator overloading</a>
<a href='#asm'>Inline assembly</a>
<a href='#cpp'>Translating C/C++ to V</a>
<a href='#hot'>Hot code reloading</a>
<a href='#cross'>Cross compilation</a>
<a href='#bash'>Cross-platform shell scripts in V</a>
<br>
<a href='#keywords'>Appendix I: Keywords</a>
<a href='#operators'>Appendix II: Operators</a>
</div>
<div class='docs'>
<h2 id=introduction style='border:0; margin-top:0; padding-top:20px;'>%introduction</h2>
V is a statically typed compiled programming language designed for building maintainable software.
<p>
It's similar to Go and is also influenced by Oberon, Rust, Swift.
<p>
V is a very simple language. Going through this documentation will take you about half an hour,
and by the end of it you will learn pretty much the entire language.
<p>
Despite being simple, it gives a lot of power to the developer. Anything you can do in other languages,
you can do in V.
<!--
<p>
V is very strict. It helps with safety, readability, and maintainability.
-->
<p>
Found an error/typo? Please <a target=_blank
href='https://github.com/vlang-io/website/blob/master/docs.html'>submit a pull request</a>.
<h2 id=hello>Hello World</h2>
<pre><key>fn</key> main() {
println(<str>'hello world'</str>)
}</pre>
<input class='run' type='button' value='Run'>
<p>
Functions are declared with <code>fn</code>. Return type goes after the function
name. In this case <code>main</code> doesn't return anything, so the type is
omitted.
<p>
Just like in C and all related languages, <code>main</code> is an entry point.
<p>
<code>println</code> is one of the few built-in functions. It prints the value
to standard output.
<p><code>fn main()</code> declaration can be skipped in one file programs.
This is useful when writing small programs, "scripts", or just learning
the language. For brevity, <code>fn main()</code> will be skipped in this
tutorial.
<p>
This means that a "hello world" program can be as simple as
<pre>
println(<str>'hello world'</str>)
</pre>
<input class='run' type='button' value='Run'>
<h2 id=comments>%comments</h2>
<pre>
<comment>// This is a single line comment.
/* This is a multiline comment.
/* It can be nested. */
*/</comment></pre>
<h2 id=fns>%functions</h2>
<pre>
<key>fn </key>main() {
println(add(77, 33))
println(sub(100, 50))
}
<key>fn </key>add(x int, y int) int {
return x + y
}
<key>fn </key>sub(x, y int) int {
return x - y
}
</pre>
<input class='run' type='button' value='Run'>
<p>
Again, the type comes after the argument's name.<!-- If two or more arguments in a row have the same type,
shorter notation can be used: <code>a</code>
can be listed
-->
<p>
Just like in Go and C, functions cannot be overloaded. This simplifies the code and improves
maintainability and readability.
<p>
Functions can be used before their declaration:
<code>add</code> and <code>sub</code> are declared after <code>main</code>, but
can still be called from <code>main</code>.
<!--
unlike C, Python, F#
-->
This is true for all declarations in V and eliminates the need of header files
or thinking about the order of files and declarations.
<h2 id=vars>%variables</h2>
<pre>
name := <str>'Bob'</str>
age := 20
large_number := i64(9999999999)
println(name)
println(age)
println(large_number)
</pre>
<input class='run' type='button' value='Run'>
<p>
Variables are declared and initialized with <code>:=</code>. This is the only
way to declare variables in V. This means that variables always have an initial
value.
<p>
The variable's type is inferred from the value on the right hand side.
To force a different type, use type conversion:
the expression <code>T(v)</code> converts the value <code>v</code> to the
type <code>T</code>.
<p>
Unlike most other languages, V only allows defining variables in functions.
Global (module level) variables are not allowed. There's no global state in V.
<!--You can read why <a href='#'> here</a>.-->
<p> </p>
<pre>
<key>mut</key> age := 20
println(age)
age = 21
println(age)
</pre>
<input class='run' type='button' value='Run'>
<p>
To change the value of the variable use <code>=</code>. In V, variables are
immutable by default. To be able to change the value of the variable, you
have to declare it with <code>mut</code>.
<p>Try compiling the program above after removing <code>mut</code> from
the first line.
<p>
Please note the difference between <code>:=</code> and <code>=</code><br> <code>:=</code>
is used for declaring and initializing, <code>=</code> is used for assigning.
<p> </p>
<pre>
<key>fn </key>main() {
age = 21
}
</pre>
<input class='run' type='button' value='Run'>
<p>
This code will not compile, because variable <code>age</code> is not declared.
All variables need to be declared in V.
<p> </p>
<pre>
<key>fn </key>main() {
age := 21
}
</pre>
<input class='run' type='button' value='Run'>
<p>
This code will not compile either, because unused variables result in a compilation error.
<p> </p>
<pre>
<key>fn </key>main() {
a := 10
if true {
a := 20
}
}
</pre>
<input class='run' type='button' value='Run'>
<p>
Unlike most languages, variable shadowing is not allowed. Declaring a variable with a name that is already
used in a parent scope will result in a compilation error.
<h2 id=btypes>%basic_types</h2>
<pre>
bool
string
i8 i16 i32 i64 i128 (soon)
u8 u16 u32 u64 u128 (soon)
byte <comment>// alias for u8 </comment>
int <comment>// alias for i32 </comment>
rune <comment>// alias for i32, represents a Unicode code point </comment>
f32 f64
byteptr
voidptr
</pre>
Please note that unlike C and Go, <code>int</code> is always a 32 bit integer.
<h2 id=strings>%strings</h2>
<pre>
name := <str>'Bob'</str>
println(<str>'Hello, </str>$name<str>!'</str>) <comment>// `$` is used for string interpolation</comment>
println(name.len)
bobby := name + <str>'by'</str> <comment>// + is used to concatenate strings</comment>
println(bobby) <comment>// ==> "Bobby" </comment>
println(bobby.substr(1, 3)) <comment>// ==> "ob" </comment>
<comment>// println(bobby[1:3]) // This syntax will most likely replace the substr() method </comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
In V, a string is a read-only array of bytes. String data is encoded using UTF-8.
<p>
Both single and double quotes can be used to denote strings (TODO: double quotes are not supported
yet). For consistency, <code>vfmt</code> converts double quotes to single quotes unless the string
contains a single quote character.
<p>
Strings are immutable. This means that the substring function is very efficient:
no copying is performed, no extra allocations required.
<p>
<p>
All operators in V must have values of the same type on both sides.
This code will not compile if <code>age</code> is an <code>int</code>:
<pre>println(<str>'age = '</str> + age)</pre>
We have to either convert <code>age</code> to a <code>string</code>:
<pre>println(<str>'age = '</str> + age.str())</pre> or use string interpolation (preferred):
<pre>println(<str>'age = $age'</str>)</pre>
<!--
or simply pass a second argument to <code>println</code>:
<pre>println(<str>'age = '</str>, age) <comment>// TODO: not implemented yet</comment></pre>
-->
<h2 id=arrays>%arrays</h2>
<pre>
<key>mut</key> nums := [1, 2, 3]
println(nums) <comment>// "[1, 2, 3]"</comment>
println(nums[1]) <comment>// "2"</comment>
nums << 4
println(nums) <comment>// "[1, 2, 3, 4]"</comment>
nums << [5, 6, 7]
println(nums) <comment>// "[1, 2, 3, 4, 5, 6, 7]"</comment>
<key>mut</key> names := [<str>'John'</str>]
names << <str>'Peter'</str>
names << <str>'Sam'</str>
<comment>// names << 10 <-- This will not compile. `names` is an array of strings.</comment>
println(names.len) <comment>// "3"</comment>
println(<str>'Alex'</str> <key>in</key> names) <comment>// "false"</comment>
<comment>// We can also preallocate a certain amount of elements.</comment>
nr_ids := 50
ids := [0 ; nr_ids] <comment>// This creates an array with 50 zeroes</comment>
<!--
for i := 0; i < nr_ids; i++ {
ids[i] = i <comment>// This is more efficient than </comment>
<comment>// ids << i</comment>
}
-->
</pre>
<input class='run' type='button' value='Run'>
<p>
Array type is determined by the first element: <code>[1, 2, 3]</code> is an array of ints <br>
(<code>[]int</code>). <br>
<code>['a', 'b']</code> is an array of strings (<code>[]string</code>).
<p>
All elements must have the same type. <code>[1, 'a']</code> will not compile.
<p>
<code><<</code> is an operator that appends a value to the end of the array.
It can also append an entire array.
<p><code>.len</code> field returns the length of the array. Note, that it's a read-only field,
and it can't be modified by the user. All exported fields are read-only by default in V.
<p><code>val in array</code> returns true if the array contains <code>val</code>.
<h2 id=maps>Maps</h2>
<pre>
<key>mut</key> m := map[string]int{} <comment>// Only maps with string keys are allowed for now </comment>
m[<str>'one'</str>] = 1
println(m[<str>'one'</str>]) <comment>// ==> "1" </comment>
println(m[<str>'bad_key'</str>]) <comment>// ==> "0" </comment>
<comment>// TODO: implement a way to check if the key exists</comment>
numbers := { <comment>// TODO: this syntax is not implemented yet </comment>
<str>'one'</str>: 1,
<str>'two'</str>: 2,
}
</pre>
<h2 id=if>If</h2>
<pre>
a := 10
b := 20
<key>if </key>a < b {
println(<str>'$a < $b'</str>)
} <key>else if </key>a > b {
println(<str>'$a > $b'</str>)
} <key>else</key> {
println(<str>'$a == $b'</str>)
}
</pre>
<input class='run' type='button' value='Run'>
<p>
<code>if</code> statements are pretty straightforward and similar to most
other languages.
<p>
Unlike other C-like languages, there are no parentheses surrounding the
condition, and the braces are always required.
</p>
<p>
<code>if</code> can be used as an expression:
<pre>
num := 777
s := <key>if</key> num % 2 == 0 {
<str>'even'</str>
}
<key>else</key> {
<str>'odd'</str>
}
println(s) <comment>// ==> "odd"</comment>
</pre>
<h2 id=in>%in_op</h2>
<code>in</code> allows to check whether an array contains an element.
<pre>nums := [1, 2, 3]
println(1 <key>in</key> nums) <comment>// ==> true</comment>
</pre>
It's also useful for writing more clear and compact boolean expressions:
<pre><key>if</key> parser.token == .plus || parser.token == .minus || parser.token == .div || parser.token == .mult {
...
}
<key>if</key> parser.token <key>in</key> [.plus, .minus, .div, .mult] {
...
}
</pre>
V optimizes such expressions, so both <code>if</code> statements above produce the same machine code,
no arrays are created.
<h2 id=for>%for_loop</h2>
V has only one looping construct: <code>for</code>.
<pre>
numbers := [1, 2, 3, 4, 5]
<key>for</key> num <key>in</key> numbers {
println(num)
}
names := [<str>'Sam'</str>, <str>'Peter'</str>]
<key>for</key> i, name <key>in</key> names {
println(<str>'$i) $name'</str>) <comment>// Output: 0) Sam</comment>
} <comment>// 1) Peter</comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
The <code>for value in</code> loop is used for going through elements of an array.
If an index is required, an alternative form <code>for index, value in</code> can be used.
<p>
Note, that the value is read-only. If you need to modify the array while looping,
you have to use indexing:
<pre>
<key>mut</key> numbers := [1, 2, 3, 4, 5]
<key>for</key> i, num <key>in</key> numbers {
println(num)
numbers[i] = 0
}
</pre>
<p> </p>
<pre>
mut sum := 0
mut i := 0
for i <= 100 {
sum += i
i++
}
println(sum) // ==> "5050"
</pre>
<input class='run' type='button' value='Run'>
<p>
This form of the loop is similar to <code>while</code>
loops in other languages.
<p>
The loop will stop iterating once the boolean condition evaluates to false.
<p>
Again, there are no parentheses surrounding the
condition, and the braces are always required.
<p> </p>
<pre>
mut num := 0
for {
num++
<key>if </key>num >= 10 {
break
}
}
println(num) // ==> "10"
</pre>
<input class='run' type='button' value='Run'>
<p>
The condition can be omitted, this results in an infinite loop.
<p> </p>
<pre>
for i := 0; i < 10; i++ {
println(i)
}
</pre>
<input class='run' type='button' value='Run'>
<p>
Finally, there's the traditional C style <code>for</code> loop. It's safer than the `while` form
because with the latter it's easy to forget to update the counter and get
stuck in an infinite loop.
<p>
Here <code>i</code> doesn't need to be declared with <code>mut</code> since it's always going to be mutable by definition.
<h2 id=switch>Switch</h2>
<pre>
os := 'windows'
print('V is running on ')
switch os {
case 'darwin':
println('macOS.')
case 'linux':
println('Linux.')
default:
println(os)
}
<comment>// TODO: replace with match expressions</comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
A switch statement is a shorter way to write a sequence of <code>if - else</code> statements. It runs the first case whose value is equal to the condition expression.
<p>
Unlike C, <code>break</code> statement is not needed at the end of every block.
<h2 id=structs>%structs</h2>
<pre>
<key>struct</key> Point {
x int
y int
}
p := Point{
x: 10
y: 20
}
println(p.x) <comment>// Struct fields are accessed using a dot</comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
<p>
Structs are allocated on the stack. To allocate a struct on the heap and get
a pointer to it, use the <code>&</code> prefix:
<pre>
pointer := &Point{10, 10} <comment>// Alternative initialization syntax for structs with 3 fields or fewer</comment>
println(pointer.x) <comment>// Pointers have the same syntax for accessing fields </comment>
</pre>
<p>
<p>
V doesn't have subclassing, but it supports embedded structs:
<pre>
<comment>// TODO: this will be implemented later in July</comment>
<key>struct</key> Button {
Widget
title string
}
button := new_button(<str>'Click me'</str>)
button.set_pos(x, y)
<comment>// Without embedding we'd have to do</comment>
button.widget.set_pos(x,y)
</pre>
<h2 id=mod>Access modifiers</h2>
<p>
Struct fields are private and immutable by default (making structs immutable as well).
Their access modifiers can be changed with
<code>pub</code> and <code>mut</code>. In total, there are 5 possible options:
<pre><key>struct</key> Foo {
a int <comment>// private immutable (default)</comment>
<key>mut</key>:
b int <comment>// private mutable</comment>
c int <comment>// (you can list multiple fields with the same access modifier) </comment>
<key>pub</key>:
d int <comment>// public immmutable (readonly)</comment>
<key>pub mut</key>:
e int <comment>// public, but mutable only in parent module </comment>
<key>pub mut mut</key>:
f int <comment>// public and mutable both inside and outside parent module </comment>
} <comment>// (not recommended to use, that's why it's so verbose)</comment>
</pre>
<p>
<p>
For example, here's the <code>string</code> type defined in the <code>builtin</code> module:
<pre>
<key>struct</key> string {
str byteptr
<key>pub</key>:
len int
}
</pre>
<p>
It's easy to see from this definition that
<code>string</code> is an immutable type.
<p>
The byte pointer with the string data is not accessible outside <code>builtin</code> at all.
<code>len</code> field is public, but not mutable.
<pre>
<key>fn</key> main() {
str := <str>'hello'</str>
len := str.len <comment>// OK </comment>
str.len++ <comment>// Compilation error </comment>
}
</pre>
<h2 id=methods>%methods</h2>
<!--
<pre>
import math
struct Point {
x int
y int
}
<key>fn </key>(a Point) distance_to(b Point) f64 {
return math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
}
p := Point{10,10}
p2 := Point{20,20}
println(p.distance_to(p2))
</pre>
-->
<pre>
struct User {
age int
}
<key>fn </key>(u User) can_register() bool {
return u.age > 16
}
user := User{age: 10}
println(user.can_register()) <comment>// ==> "false" </comment>
user2 := User{age: 20}
println(user2.can_register()) <comment>// ==> "true" </comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
V doesn't have classes. But you can define methods on types.
<p>
A method is a function with a special receiver argument.
<p>
The receiver appears in its own argument list between the <code>fn</code> keyword and the method name.
<p>
<!--
In this example, the <code>distance_to</code> method has a receiver of type <code>Point</code>
named <code>a</code>.
-->
In this example, the <code>can_register</code> method has a receiver of type <code>User</code>
named <code>u</code>. The convention is not to use receiver names like <code>self</code> or
<code>this</code>, but a short, preferably one letter long, name.
<h2 id=recvs>Pure functions by default</h2>
V functions are pure by default, meaning that their return values are only determined by
their arguments, and their evaluation has no side effects.
<p>
This is achieved by lack of global variables and all function arguments being
immutable by default, even when references are passed.
<p>
V is not a pure functional language however. It is possible to modify function arguments
by using the same keyword <code>mut</code>:
<pre><key>struct</key> User {
<key>mut</key>:
is_registered bool
}
<key>fn </key>(u <key>mut</key> User) register() {
u.is_registered = true
}
<key>mut</key> user := User{}
println(user.is_registered) <comment>// ==> "false" </comment>
user.register()
println(user.is_registered) <comment>// ==> "true" </comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
In this example, the receiver (which is simply the first argument) is marked as mutable,
so <code>register()</code> can change the user object.
The same works with non-receiver arguments:
<pre>
<key>fn</key> multiply_by_2(arr <key>mut</key> []int) {
<key>for</key> i := 0; i < arr.len; i++ {
arr[i] *= 2
}
}
<key>mut</key> nums := [1, 2, 3]
multiply_by_2(<key>mut</key> nums)
println(nums) <comment>// ==> "[2, 4, 6]"
</pre>
<p>
Note, that you have to add <code>mut</code> before <code>nums</code> when calling this function. This makes
it clear that the function being called will modify the value.
<!--
<p>
Please note that functions can only modify receivers.<br><code><key>fn </key>register(u mut User)</code>
will not compile.
<p>
This is very important, so I'll say it again: V functions are partially pure, their arguments can
never be modified by the function.
<p>
-->
<p>It is preferable to return values instead of modifying arguments.
Modifying arguments should only be done in performance-critical parts of your application
to reduce allocations and copying.
<p>
Use <code>user.register()</code> or <code>user = register(user)</code>
instead of <code>register(mut user)</code>.
<p>
V makes it easy to return a modifed version of an an object: <br>
<pre>
<key>fn </key>register(u User) User {
return { u | is_registered: true }
}
user = register(user)
</pre>
<h2 id=highfns> High order functions</h2>
TODO
<h2 id=consts>Constants</h2>
<pre>
<key>const</key> (
PI = 3.14
World = <str>'世界'</str>
)
println(PI)
println(World)
</pre>
<input class='run' type='button' value='Run'>
<p>
Constants are declared with <code>const</code>. They can only be defined
at the module level (outside of functions).
<p>
Constant names must be capitalized. This helps distinguish them from variables.
<p>
Constant values can never be changed.
<p>
V constants are more flexible than in most languages. You can assign more complex values:
<pre>
<key>struct</key> Color {
r int
g int
b int
}
<key>fn </key>(c Color) str() string { return <str>'{$c.r, $c.g, $c.b}'</str> }
<key>fn </key>rgb(r, g, b int) Color { return Color{r: r, g: g, b: b} }
<key>const</key> (
Numbers = [1, 2, 3]
Red = Color{r: 255, g: 0, b: 0}
Blue = rgb(0, 0, 255)
)
println(Numbers)
println(Red)
println(Blue)
</pre>
<input class='run' type='button' value='Run'>
<p>
Global variables are not allowed, so this can be really useful.
<h2 id=modules>Modules</h2>
V is a very modular language. Creating reusable modules is encouraged and is
very simple.
To create a new module, create a directory with your module's name and
.v files with code:
<pre>
cd ~/code/modules
mkdir mymodule
vim mymodule/mymodule.v
<comment>// mymodule.v</comment>
<key>module</key> mymodule
<comment>// To export a function we have to use `pub`</comment>
<key>pub fn</key> say_hi() {
println(<str>'hello from mymodule!'</str>)
}
</pre>
You can have as many .v files in <code>mymodule/</code> as you want.
<p>
Build it with <code>v -lib ~/code/modules/mymodule</code>.
<p>
That's it, you can now use it in your code:
<pre>
<key>module</key> main
<key>import</key> mymodule
<key>fn </key>main() {
mymodule.say_hi()
}
</pre>
<p>
Note that you have to specify the module every time you call an external function.
This may seem verbose at first, but it makes code much more readable
and easier to understand, since it's always clear which function from
which module is being called. Especially in large code bases.
<p>
Module names should be short, under 10 characters. Circular imports are not allowed.
<p>
You can create modules anywhere.
<p>
All modules are compiled statically into a single executable.
<h2 id=interfaces>Interfaces</h2>
<pre>
<key>struct</key> Dog {}
<key>struct</key> Cat {}
<key>fn </key>(d Dog) speak() string {
return <str>'woof'</str>
}
<key>fn </key>(c Cat) speak() string {
return <str>'meow' </str>
}
<key>interface</key> Speaker {
speak() string
}
<key>fn </key>perform(s Speaker) {
println(s.speak())
}
dog := Dog{}
cat := Cat{}
perform(dog) <comment>// ==> "woof" </comment>
perform(cat) <comment>// ==> "meow" </comment>
</pre>
<input class='run' type='button' value='Run'>
<p>
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword.
</p>
<!--
<p>
V interfaces are very efficient. There's no dynamic dispatch.
</p>