instruction stringlengths 52 128 | input stringclasses 1
value | output stringlengths 1 8.58k |
|---|---|---|
Explain the following V language topic in detail: Running a project folder with several files | Suppose you have a folder with several .v files in it, where one of them
contains your `main()` function, and the other files have other helper
functions. They may be organized by topic, but still _not yet_ structured
enough to be their own separate reusable modules, and you want to compile
them all into one program.
... | |
Explain the following V language topic in detail: Comments | ```v
// This is a single line comment.
/*
This is a multiline comment.
/* It can be nested. */
*/
``` | |
Explain the following V language topic in detail: Functions | ```v
fn main() {
println(add(77, 33))
println(sub(100, 50))
}
fn add(x int, y int) int {
return x + y
}
fn sub(x int, y int) int {
return x - y
}
```
Again, the type comes after the argument's name.
Just like in Go and C, functions cannot be overloaded.
This simplifies the code and improves maintainability and ... | |
Explain the following V language topic in detail: Hoisting | Functions can be used before their declaration:
`add` and `sub` are declared after `main`, but can still be called from `main`.
This is true for all declarations in V and eliminates the need for header files
or thinking about the order of files and declarations.
# | |
Explain the following V language topic in detail: Returning multiple values | ```v
fn foo() (int, int) {
return 2, 3
}
a, b := foo()
println(a) // 2
println(b) // 3
c, _ := foo() // ignore values using `_`
``` | |
Explain the following V language topic in detail: Symbol visibility | ```v
pub fn public_function() {
}
fn private_function() {
}
```
Functions are private (not exported) by default.
To allow other [modules](#module-imports) to use them, prepend `pub`. The same applies
to [structs](#structs), [constants](#constants) and [types](#type-declarations).
> [!NOTE] > `pub` can only be used f... | |
Explain the following V language topic in detail: Variables | ```v
name := 'Bob'
age := 20
large_number := i64(9999999999)
println(name)
println(age)
println(large_number)
```
Variables are declared and initialized with `:=`. This is the only
way to declare variables in V. This means that variables always have an initial
value.
The variable's type is inferred from the value on ... | |
Explain the following V language topic in detail: Mutable variables | ```v
mut age := 20
println(age)
age = 21
println(age)
```
To change the value of the variable use `=`. In V, variables are
immutable by default.
To be able to change the value of the variable, you have to declare it with `mut`.
Try compiling the program above after removing `mut` from the first line.
# | |
Explain the following V language topic in detail: Initialization vs assignment | Note the (important) difference between `:=` and `=`.
`:=` is used for declaring and initializing, `=` is used for assigning.
```v failcompile
fn main() {
age = 21
}
```
This code will not compile, because the variable `age` is not declared.
All variables need to be declared in V.
```v
fn main() {
age := 21
}
```
... | |
Explain the following V language topic in detail: Warnings and declaration errors | In development mode the compiler will warn you that you haven't used the variable
(you'll get an "unused variable" warning).
In production mode (enabled by passing the `-prod` flag to v – `v -prod foo.v`)
it will not compile at all (like in Go).
```v
fn main() {
a := 10
// warning: unused variable `a`
}
```
To igno... | |
Explain the following V language topic in detail: V Types | # | |
Explain the following V language topic in detail: Primitive types | ```v ignore
bool
string
i8 i16 int i64 i128 (soon)
u8 u16 u32 u64 u128 (soon)
rune // represents a Unicode code point
f32 f64
isize, usize // platform-dependent, the size is how many bytes it takes to reference any location in memory
voidptr // this one is mostly used for [C interoperability](... | |
Explain the following V language topic in detail: Strings | In V, strings are encoded in UTF-8, and are immutable (read-only) by default:
```v
s := 'hello 🌎' // the `world` emoji takes 4 bytes, and string length is reported in bytes
assert s.len == 10
arr := s.bytes() // convert `string` to `[]u8`
assert arr.len == 10
s2 := arr.bytestr() // convert `[]u8` to `string`
assert... | |
Explain the following V language topic in detail: String interpolation | Basic interpolation syntax is pretty simple - use `${` before a variable name and `}` after. The
variable will be converted to a string and embedded into the literal:
```v
name := 'Bob'
println('Hello, ${name}!') // Hello, Bob!
```
It also works with fields: `'age = ${user.age}'`. You may also use more complex expres... | |
Explain the following V language topic in detail: String operators | ```v
name := 'Bob'
bobby := name + 'by' // + is used to concatenate strings
println(bobby) // "Bobby"
mut s := 'hello '
s += 'world' // `+=` is used to append to a string
println(s) // "hello world"
```
All operators in V must have values of the same type on both sides. You cannot concatenate an
integer to a string:
... | |
Explain the following V language topic in detail: Runes | A `rune` represents a single UTF-32 encoded Unicode character and is an alias for `u32`.
To denote them, use <code>`</code> (backticks) :
```v
rocket := `🚀`
```
A `rune` can be converted to a UTF-8 string by using the `.str()` method.
```v
rocket := `🚀`
assert rocket.str() == '🚀'
```
A `rune` can be converted to... | |
Explain the following V language topic in detail: Numbers | ```v
a := 123
```
This will assign the value of 123 to `a`. By default `a` will have the
type `int`.
You can also use hexadecimal, binary or octal notation for integer literals:
```v
a := 0x7B
b := 0b01111011
c := 0o173
```
All of these will be assigned the same value, 123. They will all have type
`int`, no matter ... | |
Explain the following V language topic in detail: Arrays | An array is a collection of data elements of the same type. An array literal is a
list of expressions surrounded by square brackets. An individual element can be
accessed using an _index_ expression. Indexes start from `0`:
```v
mut nums := [1, 2, 3]
println(nums) // `[1, 2, 3]`
println(nums[0]) // `1`
println(nums[1]... | |
Explain the following V language topic in detail: Array Fields | There are two fields that control the "size" of an array:
- `len`: _length_ - the number of pre-allocated and initialized elements in the array
- `cap`: _capacity_ - the amount of memory space which has been reserved for elements,
but not initialized or counted as elements. The array can grow up to this size without... | |
Explain the following V language topic in detail: Array Initialization | The type of an array is determined by the first element:
- `[1, 2, 3]` is an array of ints (`[]int`).
- `['a', 'b']` is an array of strings (`[]string`).
The user can explicitly specify the type for the first element: `[u8(16), 32, 64, 128]`.
V arrays are homogeneous (all elements must have the same type).
This means... | |
Explain the following V language topic in detail: Array Types | An array can be of these types:
| Types | Example Definition |
| ------------ | ------------------------------------ |
| Number | `[]int,[]i64` |
| String | `[]string` |
| Rune | `[]rune` |
| Boole... | |
Explain the following V language topic in detail: Multidimensional Arrays | Arrays can have more than one dimension.
2d array example:
```v
mut a := [][]int{len: 2, init: []int{len: 3}}
a[0][1] = 2
println(a) // [[0, 2, 0], [0, 0, 0]]
```
3d array example:
```v
mut a := [][][]int{len: 2, init: [][]int{len: 3, init: []int{len: 2}}}
a[0][1][1] = 2
println(a) // [[[0, 0], [0, 2], [0, 0]], [[0... | |
Explain the following V language topic in detail: Array methods | All arrays can be easily printed with `println(arr)` and converted to a string
with `s := arr.str()`.
Copying the data from the array is done with `.clone()`:
```v
nums := [1, 2, 3]
nums_copy := nums.clone()
```
Arrays can be efficiently filtered and mapped with the `.filter()` and
`.map()` methods:
```v
nums := [1... | |
Explain the following V language topic in detail: Sorting Arrays | Sorting arrays of all kinds is very simple and intuitive. Special variables `a` and `b`
are used when providing a custom sorting condition.
```v
mut numbers := [1, 3, 2]
numbers.sort() // 1, 2, 3
numbers.sort(a > b) // 3, 2, 1
```
```v
struct User {
age int
name string
}
mut users := [User{21, 'Bob'}, User{20, 'Z... | |
Explain the following V language topic in detail: Array Slices | A slice is a part of a parent array. Initially it refers to the elements
between two indices separated by a `..` operator. The right-side index must
be greater than or equal to the left side index.
If a right-side index is absent, it is assumed to be the array length. If a
left-side index is absent, it is assumed to b... | |
Explain the following V language topic in detail: Slices with negative indexes | V supports array and string slices with negative indexes.
Negative indexing starts from the end of the array towards the start,
for example `-3` is equal to `array.len - 3`.
Negative slices have a different syntax from normal slices, i.e. you need
to add a `gate` between the array name and the square bracket: `a#[..-3]... | |
Explain the following V language topic in detail: Array method chaining | You can chain the calls of array methods like `.filter()` and `.map()` and use
the `it` built-in variable to achieve a classic `map/filter` functional paradigm:
```v
// using filter, map and negatives array slices
files := ['pippo.jpg', '01.bmp', '_v.txt', 'img_02.jpg', 'img_01.JPG']
filtered := files.filter(it#[-4..]... | |
Explain the following V language topic in detail: Fixed size arrays | V also supports arrays with fixed size. Unlike ordinary arrays, their
length is constant. You cannot append elements to them, nor shrink them.
You can only modify their elements in place.
However, access to the elements of fixed size arrays is more efficient,
they need less memory than ordinary arrays, and unlike ordi... | |
Explain the following V language topic in detail: Maps | ```v
mut m := map[string]int{} // a map with `string` keys and `int` values
m['one'] = 1
m['two'] = 2
println(m['one']) // "1"
println(m['bad_key']) // "0"
println('bad_key' in m) // Use `in` to detect whether such key exists
println(m.keys()) // ['one', 'two']
m.delete('two')
```
Maps can have keys of type string, ru... | |
Explain the following V language topic in detail: Map update syntax | As with structs, V lets you initialise a map with an update applied on top of
another map:
```v
const base_map = {
'a': 4
'b': 5
}
foo := {
...base_map
'b': 88
'c': 99
}
println(foo) // {'a': 4, 'b': 88, 'c': 99}
```
This is functionally equivalent to cloning the map and updating it, except that
you don't have... | |
Explain the following V language topic in detail: Module imports | For information about creating a module, see [Modules](#modules).
Modules can be imported using the `import` keyword:
```v
import os
fn main() {
// read text from stdin
name := os.input('Enter your name: ')
println('Hello, ${name}!')
}
```
This program can use any public definitions from the `os` module, such
as... | |
Explain the following V language topic in detail: Selective imports | You can also import specific functions and types from modules directly:
```v
import os { input }
fn main() {
// read text from stdin
name := input('Enter your name: ')
println('Hello, ${name}!')
}
```
> [!NOTE]
> This will import the module as well. Also, this is not allowed for
> constants - they must always be ... | |
Explain the following V language topic in detail: Module hierarchy | > [!NOTE]
> This section is valid when .v files are not in the project's root directory.
Modules names in .v files, must match the name of their directory.
A .v file `./abc/source.v` must start with `module abc`. All .v files in this directory
belong to the same module `abc`. They should also start with `module abc`.... | |
Explain the following V language topic in detail: Module import aliasing | Any imported module name can be aliased using the `as` keyword:
> [!NOTE]
> This example will not compile unless you have created `mymod/sha256/somename.v`
> (submodule names are determined by their path, not by the names of the .v file(s) in them).
```v failcompile
import crypto.sha256
import mymod.sha256 as mysha25... | |
Explain the following V language topic in detail: Statements & expressions | # | |
Explain the following V language topic in detail: If | ```v
a := 10
b := 20
if a < b {
println('${a} < ${b}')
} else if a > b {
println('${a} > ${b}')
} else {
println('${a} == ${b}')
}
```
`if` statements are pretty straightforward and similar to most other languages.
Unlike other C-like languages,
there are no parentheses surrounding the condition and the braces are ... | |
Explain the following V language topic in detail: `If` expressions | Unlike C, V does not have a ternary operator, that would allow you to do: `x = c ? 1 : 2` .
Instead, it has a bit more verbose, but also clearer to read, ability to use `if` as an
expression. The direct translation in V of the ternary construct above, assuming `c` is a
boolean condition, would be: `x = if c { 1 } else ... | |
Explain the following V language topic in detail: `If` unwrapping | Anywhere you can use `or {}`, you can also use "if unwrapping". This binds the unwrapped value
of an expression to a variable when that expression is not none nor an error.
```v
m := {
'foo': 'bar'
}
// handle missing keys
if v := m['foo'] {
println(v) // bar
} else {
println('not found')
}
```
```v
fn res() !int... | |
Explain the following V language topic in detail: Type checks and casts | You can check the current type of a sum type using `is` and its negated form `!is`.
You can do it either in an `if`:
```v cgen
struct Abc {
val string
}
struct Xyz {
foo string
}
type Alphabet = Abc | Xyz
x := Alphabet(Abc{'test'}) // sum type
if x is Abc {
// x is automatically cast to Abc and can be used here... | |
Explain the following V language topic in detail: Match | ```v
os := 'windows'
print('V is running on ')
match os {
'darwin' { println('macOS.') }
'linux' { println('Linux.') }
else { println(os) }
}
```
A match statement is a shorter way to write a sequence of `if - else` statements.
When a matching branch is found, the following statement block will be run.
The else bra... | |
Explain the following V language topic in detail: In operator | `in` allows to check whether an array or a map contains an element.
To do the opposite, use `!in`.
```v
nums := [1, 2, 3]
println(1 in nums) // true
println(4 !in nums) // true
```
> [!NOTE] > `in` checks if map contains a key, not a value.
```v
m := {
'one': 1
'two': 2
}
println('one' in m) // true
println('thre... | |
Explain the following V language topic in detail: For loop | V has only one looping keyword: `for`, with several forms.
## | |
Explain the following V language topic in detail: `for`/`in` | This is the most common form. You can use it with an array, map or
numeric range.
### | |
Explain the following V language topic in detail: Array `for` | ```v
numbers := [1, 2, 3, 4, 5]
for num in numbers {
println(num)
}
names := ['Sam', 'Peter']
for i, name in names {
println('${i}) ${name}')
// Output: 0) Sam
// 1) Peter
}
```
The `for value in arr` form is used for going through elements of an array.
If an index is required, an alternative form `for ind... | |
Explain the following V language topic in detail: Custom iterators | Types that implement a `next` method returning an `Option` can be iterated
with a `for` loop.
```v
struct SquareIterator {
arr []int
mut:
idx int
}
fn (mut iter SquareIterator) next() ?int {
if iter.idx >= iter.arr.len {
return none
}
defer {
iter.idx++
}
return iter.arr[iter.idx] * iter.arr[iter.idx]
}
n... | |
Explain the following V language topic in detail: Map `for` | ```v
m := {
'one': 1
'two': 2
}
for key, value in m {
println('${key} -> ${value}')
// Output: one -> 1
// two -> 2
}
```
Either key or value can be ignored by using a single underscore as the identifier.
```v
m := {
'one': 1
'two': 2
}
// iterate over keys
for key, _ in m {
println(key)
// Output: o... | |
Explain the following V language topic in detail: Range `for` | ```v
// Prints '01234'
for i in 0 .. 5 {
print(i)
}
```
`low..high` means an _exclusive_ range, which represents all values
from `low` up to _but not including_ `high`.
> [!NOTE]
> This exclusive range notation and zero-based indexing follow principles of
> logical consistency and error reduction. As Edsger W. Dijks... | |
Explain the following V language topic in detail: Condition `for` | ```v
mut sum := 0
mut i := 0
for i <= 100 {
sum += i
i++
}
println(sum) // "5050"
```
This form of the loop is similar to `while` loops in other languages.
The loop will stop iterating once the boolean condition evaluates to false.
Again, there are no parentheses surrounding the condition, and the braces are always ... | |
Explain the following V language topic in detail: Bare `for` | ```v
mut num := 0
for {
num += 2
if num >= 10 {
break
}
}
println(num) // "10"
```
The condition can be omitted, resulting in an infinite loop.
## | |
Explain the following V language topic in detail: C `for` | ```v
for i := 0; i < 10; i += 2 {
// Don't print 6
if i == 6 {
continue
}
println(i)
}
```
Finally, there's the traditional C style `for` 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.
Here `i` doesn't need to be declar... | |
Explain the following V language topic in detail: Labelled break & continue | `break` and `continue` control the innermost `for` loop by default.
You can also use `break` and `continue` followed by a label name to refer to an outer `for`
loop:
```v
outer: for i := 4; true; i++ {
println(i)
for {
if i < 7 {
continue outer
} else {
break outer
}
}
}
```
The label must immediately ... | |
Explain the following V language topic in detail: Defer | A defer statement defers the execution of a block of statements
until the surrounding function returns.
```v
import os
fn read_log() {
mut ok := false
mut f := os.open('log.txt') or { panic(err) }
defer {
f.close()
}
// ...
if !ok {
// defer statement will be called here, the file will be closed
return
}... | |
Explain the following V language topic in detail: Goto | V allows unconditionally jumping to a label with `goto`. The label name must be contained
within the same function as the `goto` statement. A program may `goto` a label outside
or deeper than the current scope. `goto` allows jumping past variable initialization or
jumping back to code that accesses memory that has alre... | |
Explain the following V language topic in detail: Structs | ```v
struct Point {
x int
y int
}
mut p := Point{
x: 10
y: 20
}
println(p.x) // Struct fields are accessed using a dot
// Alternative literal syntax
p = Point{10, 20}
assert p.x == 10
```
Struct fields can re-use reserved keywords:
```v
struct Employee {
type string
name string
}
employee := Employee{
type: ... | |
Explain the following V language topic in detail: Heap structs | Structs are allocated on the stack. To allocate a struct on the heap
and get a [reference](#references) to it, use the `&` prefix:
```v
struct Point {
x int
y int
}
p := &Point{10, 10}
// References have the same syntax for accessing fields
println(p.x)
```
The type of `p` is `&Point`. It's a [reference](#referenc... | |
Explain the following V language topic in detail: Default field values | ```v
struct Foo {
n int // n is 0 by default
s string // s is '' by default
a []int // a is `[]int{}` by default
pos int = -1 // custom default value
}
```
All struct fields are zeroed by default during the creation of the struct.
Array and map fields are allocated.
In case of reference value, see [here]... | |
Explain the following V language topic in detail: Required fields | ```v
struct Foo {
n int @[required]
}
```
You can mark a struct field with the `[required]` [attribute](#attributes), to tell V that
that field must be initialized when creating an instance of that struct.
This example will not compile, since the field `n` isn't explicitly initialized:
```v failcompile
_ = Foo{}
``... | |
Explain the following V language topic in detail: Short struct literal syntax | ```v
struct Point {
x int
y int
}
mut p := Point{
x: 10
y: 20
}
p = Point{
x: 30
y: 4
}
assert p.y == 4
//
// array: first element defines type of array
points := [Point{10, 20}, Point{20, 30}, Point{40, 50}]
println(points) // [Point{x: 10, y: 20}, Point{x: 20, y: 30}, Point{x: 40,y: 50}]
```
Omitting the stru... | |
Explain the following V language topic in detail: Struct update syntax | V makes it easy to return a modified version of an object:
```v
struct User {
name string
age int
is_registered bool
}
fn register(u User) User {
return User{
...u
is_registered: true
}
}
mut user := User{
name: 'abc'
age: 23
}
user = register(user)
println(user)
```
# | |
Explain the following V language topic in detail: Trailing struct literal arguments | V doesn't have default function arguments or named arguments, for that trailing struct
literal syntax can be used instead:
```v
@[params]
struct ButtonConfig {
text string
is_disabled bool
width int = 70
height int = 20
}
struct Button {
text string
width int
height int
}
fn new_button(c ... | |
Explain the following V language topic in detail: Access modifiers | Struct fields are private and immutable by default (making structs immutable as well).
Their access modifiers can be changed with
`pub` and `mut`. In total, there are 5 possible options:
```v
struct Foo {
a int // private immutable (default)
mut:
b int // private mutable
c int // (you can list multiple fields with ... | |
Explain the following V language topic in detail: Anonymous structs | V supports anonymous structs: structs that don't have to be declared separately
with a struct name.
```v
struct Book {
author struct {
name string
age int
}
title string
}
book := Book{
author: struct {
name: 'Samantha Black'
age: 24
}
}
assert book.author.name == 'Samantha Black'
assert book.author.a... | |
Explain the following V language topic in detail: Static type methods | V now supports static type methods like `User.new()`. These are defined on a struct via
`fn [Type name].[function name]` and allow to organize all functions related to a struct:
```v oksyntax
struct User {}
fn User.new() User {
return User{}
}
user := User.new()
```
This is an alternative to factory functions like... | |
Explain the following V language topic in detail: `[noinit]` structs | V supports `[noinit]` structs, which are structs that cannot be initialised outside the module
they are defined in. They are either meant to be used internally or they can be used externally
through _factory functions_.
For an example, consider the following source in a directory `sample`:
```v oksyntax
module sample... | |
Explain the following V language topic in detail: Methods | ```v
struct User {
age int
}
fn (u User) can_register() bool {
return u.age > 16
}
user := User{
age: 10
}
println(user.can_register()) // "false"
user2 := User{
age: 20
}
println(user2.can_register()) // "true"
```
V doesn't have classes, but you can define methods on types.
A method is a function with a specia... | |
Explain the following V language topic in detail: Embedded structs | V supports embedded structs.
```v
struct Size {
mut:
width int
height int
}
fn (s &Size) area() int {
return s.width * s.height
}
struct Button {
Size
title string
}
```
With embedding, the struct `Button` will automatically get all the fields and methods from
the struct `Size`, which allows you to do:
```v ... | |
Explain the following V language topic in detail: Unions | Just like structs, unions support embedding.
```v
struct Rgba32_Component {
r u8
g u8
b u8
a u8
}
union Rgba32 {
Rgba32_Component
value u32
}
clr1 := Rgba32{
value: 0x008811FF
}
clr2 := Rgba32{
Rgba32_Component: Rgba32_Component{
a: 128
}
}
sz := sizeof(Rgba32)
unsafe {
println('Size: ${sz}B,clr1.b: ${... | |
Explain the following V language topic in detail: Functions 2 | # | |
Explain the following V language topic in detail: Immutable function args by default | In V function arguments are immutable by default, and mutable args have to be
marked on call.
Since there are also no globals, that means that the return values of the functions,
are a function of their arguments only, and their evaluation has no side effects
(unless the function uses I/O).
Function arguments are imm... | |
Explain the following V language topic in detail: Mutable arguments | It is possible to modify function arguments by declaring them with the keyword `mut`:
```v
struct User {
name string
mut:
is_registered bool
}
fn (mut u User) register() {
u.is_registered = true
}
mut user := User{}
println(user.is_registered) // "false"
user.register()
println(user.is_registered) // "true"
```
... | |
Explain the following V language topic in detail: Variable number of arguments | V supports functions that receive an arbitrary, variable amounts of arguments, denoted with the
`...` prefix.
Below, `a ...int` refers to an arbitrary amount of parameters that will be collected
into an array named `a`.
```v
fn sum(a ...int) int {
mut total := 0
for x in a {
total += x
}
return total
}
println(... | |
Explain the following V language topic in detail: Anonymous & higher order functions | ```v
fn sqr(n int) int {
return n * n
}
fn cube(n int) int {
return n * n * n
}
fn run(value int, op fn (int) int) int {
return op(value)
}
fn main() {
// Functions can be passed to other functions
println(run(5, sqr)) // "25"
// Anonymous functions can be declared inside other functions:
double_fn := fn (n i... | |
Explain the following V language topic in detail: Closures | V supports closures too.
This means that anonymous functions can inherit variables from the scope they were created in.
They must do so explicitly by listing all variables that are inherited.
```v oksyntax
my_int := 1
my_closure := fn [my_int] () {
println(my_int)
}
my_closure() // prints 1
```
Inherited variables a... | |
Explain the following V language topic in detail: Parameter evaluation order | The evaluation order of the parameters of function calls is _NOT_ guaranteed.
Take for example the following program:
```v
fn f(a1 int, a2 int, a3 int) {
dump(a1 + a2 + a3)
}
fn main() {
f(dump(100), dump(200), dump(300))
}
```
V currently does not guarantee that it will print 100, 200, 300 in that order.
The only... | |
Explain the following V language topic in detail: References | ```v
struct Foo {}
fn (foo Foo) bar_method() {
// ...
}
fn bar_function(foo Foo) {
// ...
}
```
If a function argument is immutable (like `foo` in the examples above)
V can pass it either by value or by reference. The compiler will decide,
and the developer doesn't need to think about it.
You no longer need to re... | |
Explain the following V language topic in detail: Constants | ```v
const pi = 3.14
const world = '世界'
println(pi)
println(world)
```
Constants are declared with `const`. They can only be defined
at the module level (outside of functions).
Constant values can never be changed. You can also declare a single
constant separately:
```v
const e = 2.71828
```
V constants are more fl... | |
Explain the following V language topic in detail: Required module prefix | When naming constants, `snake_case` must be used. In order to distinguish consts
from local variables, the full path to consts must be specified. For example,
to access the PI const, full `math.pi` name must be used both outside the `math`
module, and inside it. That restriction is relaxed only for the `main` module
(t... | |
Explain the following V language topic in detail: Builtin functions | Some functions are builtin like `println`. Here is the complete list:
```v ignore
fn print(s string) // prints anything on stdout
fn println(s string) // prints anything and a newline on stdout
fn eprint(s string) // same as print(), but uses stderr
fn eprintln(s string) // same as println(), but uses stderr
fn exit... | |
Explain the following V language topic in detail: println | `println` is a simple yet powerful builtin function, that can print anything:
strings, numbers, arrays, maps, structs.
```v
struct User {
name string
age int
}
println(1) // "1"
println('hi') // "hi"
println([1, 2, 3]) // "[1, 2, 3]"
println(User{ name: 'Bob', age: 20 }) // "User{name:'Bob', age:20}"
```
See also... | |
Explain the following V language topic in detail: Printing custom types | If you want to define a custom print value for your type, simply define a
`str() string` method:
```v
struct Color {
r int
g int
b int
}
pub fn (c Color) str() string {
return '{${c.r}, ${c.g}, ${c.b}}'
}
red := Color{
r: 255
g: 0
b: 0
}
println(red)
```
# | |
Explain the following V language topic in detail: Dumping expressions at runtime | You can dump/trace the value of any V expression using `dump(expr)`.
For example, save this code sample as `factorial.v`, then run it with
`v run factorial.v`:
```v
fn factorial(n u32) u32 {
if dump(n <= 1) {
return dump(1)
}
return dump(n * factorial(n - 1))
}
fn main() {
println(factorial(5))
}
```
You will ... | |
Explain the following V language topic in detail: Modules | Every file in the root of a folder is part of the same module.
Simple programs don't need to specify module name, in which case it defaults to 'main'.
See [symbol visibility](#symbol-visibility), [Access modifiers](#access-modifiers).
# | |
Explain the following V language topic in detail: Create modules | V is a very modular language. Creating reusable modules is encouraged and is
quite easy to do.
To create a new module, create a directory with your module's name containing
.v files with code:
```shell
cd ~/code/modules
mkdir mymodule
vim mymodule/myfile.v
```
```v failcompile
// myfile.v
module mymodule
// To expor... | |
Explain the following V language topic in detail: Special considerations for project folders | For the top level project folder (the one, compiled with `v .`), and _only_
that folder, you can have several .v files, that may be mentioning different modules
with `module main`, `module abc` etc
This is to ease the prototyping workflow in that folder:
- you can start developing some new project with a single .v fi... | |
Explain the following V language topic in detail: `init` functions | If you want a module to automatically call some setup/initialization code when it is imported,
you can define a module `init` function:
```v
fn init() {
// your setup code here ...
}
```
The `init` function cannot be public - it will be called automatically by V, _just once_, no matter
how many times the module was ... | |
Explain the following V language topic in detail: `cleanup` functions | If you want a module to automatically call some cleanup/deinitialization code, when your program
ends, you can define a module `cleanup` function:
```v
fn cleanup() {
// your deinitialisation code here ...
}
```
Just like the `init` function, the `cleanup` function for a module cannot be public - it will be
called a... | |
Explain the following V language topic in detail: Type Declarations | # | |
Explain the following V language topic in detail: Type aliases | To define a new type `NewType` as an alias for `ExistingType`,
do `type NewType = ExistingType`.<br/>
This is a special case of a [sum type](#sum-types) declaration.
# | |
Explain the following V language topic in detail: Enums | An enum is a group of constant integer values, each having its own name,
whose values start at 0 and increase by 1 for each name listed.
For example:
```v
enum Color as u8 {
red // the default start value is 0
green // the value is automatically incremented to 1
blue // the final value is now 2
}
mut color := C... | |
Explain the following V language topic in detail: Function Types | You can use type aliases for naming specific function signatures - for
example:
```v
type Filter = fn (string) string
```
This works like any other type - for example, a function can accept an
argument of a function type:
```v
type Filter = fn (string) string
fn filter(s string, f Filter) string {
return f(s)
}
``... | |
Explain the following V language topic in detail: Interfaces | ```v
// interface-example.1
struct Dog {
breed string
}
fn (d Dog) speak() string {
return 'woof'
}
struct Cat {
breed string
}
fn (c Cat) speak() string {
return 'meow'
}
// unlike Go, but like TypeScript, V's interfaces can define both fields and methods.
interface Speaker {
breed string
speak() string
}
f... | |
Explain the following V language topic in detail: Implement an interface | A type implements an interface by implementing its methods and fields.
An interface can have a `mut:` section. Implementing types will need
to have a `mut` receiver, for methods declared in the `mut:` section
of an interface.
```v
// interface-example.2
module main
interface Foo {
write(string) string
}
// => the ... | |
Explain the following V language topic in detail: Casting an interface | We can test the underlying type of an interface using dynamic cast operators.
> [!NOTE]
> Dynamic cast converts variable `s` into a pointer inside the `if` statements in this example:
```v oksyntax
// interface-example.3 (continued from interface-example.1)
interface Something {}
fn announce(s Something) {
if s is ... | |
Explain the following V language topic in detail: Interface method definitions | Also unlike Go, an interface can have its own methods, similar to how
structs can have their methods. These 'interface methods' do not have
to be implemented, by structs which implement that interface.
They are just a convenient way to write `i.some_function()` instead of
`some_function(i)`, similar to how struct metho... | |
Explain the following V language topic in detail: Embedded interface | Interfaces support embedding, just like structs:
```v
pub interface Reader {
mut:
read(mut buf []u8) ?int
}
pub interface Writer {
mut:
write(buf []u8) ?int
}
// ReaderWriter embeds both Reader and Writer.
// The effect is the same as copy/pasting all of the
// Reader and all of the Writer methods/fields into
// R... | |
Explain the following V language topic in detail: Sum types | A sum type instance can hold a value of several different types. Use the `type`
keyword to declare a sum type:
```v
struct Moon {}
struct Mars {}
struct Venus {}
type World = Mars | Moon | Venus
sum := World(Moon{})
assert sum.type_name() == 'Moon'
println(sum)
```
The built-in method `type_name` returns the name... | |
Explain the following V language topic in detail: Dynamic casts | To check whether a sum type instance holds a certain type, use `sum is Type`.
To cast a sum type to one of its variants you can use `sum as Type`:
```v
struct Moon {}
struct Mars {}
struct Venus {}
type World = Mars | Moon | Venus
fn (m Mars) dust_storm() bool {
return true
}
fn main() {
mut w := World(Moon{})
... | |
Explain the following V language topic in detail: Smart casting | ```v oksyntax
if w is Mars {
assert typeof(w).name == 'Mars'
if w.dust_storm() {
println('bad weather!')
}
}
```
`w` has type `Mars` inside the body of the `if` statement. This is
known as _flow-sensitive typing_.
If `w` is a mutable identifier, it would be unsafe if the compiler smart casts it without a warning.... | |
Explain the following V language topic in detail: Matching sum types | You can also use `match` to determine the variant:
```v
struct Moon {}
struct Mars {}
struct Venus {}
type World = Mars | Moon | Venus
fn open_parachutes(n int) {
println(n)
}
fn land(w World) {
match w {
Moon {} // no atmosphere
Mars {
// light atmosphere
open_parachutes(3)
}
Venus {
// heavy ... | |
Explain the following V language topic in detail: Option/Result types and error handling | Option types are for types which may represent `none`. Result types may
represent an error returned from a function.
`Option` types are declared by prepending `?` to the type name: `?Type`.
`Result` types use `!`: `!Type`.
```v
struct User {
id int
name string
}
struct Repo {
users []User
}
fn (r Repo) find_us... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 39