| 1 | // usage test: v ast path_to_v/cmd/tools/vast/test/demo.v |
| 2 | // will generate demo.json |
| 3 | |
| 4 | // comment for module |
| 5 | module main |
| 6 | |
| 7 | // import module |
| 8 | import os |
| 9 | import math |
| 10 | import time { Time, now } |
| 11 | |
| 12 | // const decl |
| 13 | const a = 1 |
| 14 | const b = 3 |
| 15 | const c = 'c' |
| 16 | |
| 17 | // struct decl |
| 18 | struct Point { |
| 19 | x int |
| 20 | mut: |
| 21 | y int |
| 22 | pub: |
| 23 | z int |
| 24 | pub mut: |
| 25 | name string |
| 26 | } |
| 27 | |
| 28 | // method of Point |
| 29 | pub fn (p Point) get_x() int { |
| 30 | return p.x |
| 31 | } |
| 32 | |
| 33 | // embed struct |
| 34 | struct MyPoint { |
| 35 | Point |
| 36 | title string |
| 37 | } |
| 38 | |
| 39 | // enum type |
| 40 | enum Color { |
| 41 | red |
| 42 | green |
| 43 | blue |
| 44 | } |
| 45 | |
| 46 | // type alias |
| 47 | type Myint = int |
| 48 | |
| 49 | // sum type |
| 50 | type MySumType = bool | int | string |
| 51 | |
| 52 | // function type |
| 53 | type Myfn = fn (int) int |
| 54 | |
| 55 | // interface type |
| 56 | interface Myinterfacer { |
| 57 | add(int, int) int |
| 58 | sub(int, int) int |
| 59 | } |
| 60 | |
| 61 | // main function |
| 62 | fn main() { |
| 63 | add(1, 3) |
| 64 | println(add(1, 2)) |
| 65 | println('ok') // comment println |
| 66 | arr := [1, 3, 5, 7] |
| 67 | for a in arr { |
| 68 | println(a) |
| 69 | add(1, 3) |
| 70 | } |
| 71 | color := Color.red |
| 72 | println(color) |
| 73 | println(os.args) |
| 74 | m := math.max(1, 3) |
| 75 | println(m) |
| 76 | println(now()) |
| 77 | t := Time{} |
| 78 | println(t) |
| 79 | p := Point{ |
| 80 | x: 1 |
| 81 | y: 2 |
| 82 | z: 3 |
| 83 | } |
| 84 | println(p) |
| 85 | my_point := MyPoint{ |
| 86 | // x: 1 |
| 87 | // y: 3 |
| 88 | // z: 5 |
| 89 | } |
| 90 | println(my_point.get_x()) |
| 91 | } |
| 92 | |
| 93 | // normal function |
| 94 | fn add(x int, y int) int { |
| 95 | return x + y |
| 96 | } |
| 97 | |
| 98 | // function with defer stmt |
| 99 | fn defer_fn() { |
| 100 | mut x := 1 |
| 101 | println('start fn') |
| 102 | defer { |
| 103 | println('in defer block') |
| 104 | println(x) |
| 105 | } |
| 106 | println('end fn') |
| 107 | } |
| 108 | |
| 109 | // generic function |
| 110 | fn g_fn[T](p T) T { |
| 111 | return p |
| 112 | } |
| 113 | |
| 114 | // generic struct |
| 115 | struct GenericStruct[T] { |
| 116 | point Point |
| 117 | mut: |
| 118 | model T |
| 119 | } |
| 120 | |
| 121 | // generic interface |
| 122 | interface Gettable[T] { |
| 123 | get() T |
| 124 | } |
| 125 | |
| 126 | // generic sumtype |
| 127 | struct None {} |
| 128 | |
| 129 | type MyOption[T] = Error | None | T |
| 130 | |