Search…
Strings
In V one can define strings using the := operator. Strings (like other variables) are immutable by default. One is free to use "" or '' to denote a string. When using vfmt all double-quoted strings will be converted to single-quoted ones unless it contains a single quote character.
1
name := 'Bob'
2
println(name) // Bob
3
println(name.len) // 3
Copied!
Getting the length of a string works with .len.

Interpolation

It is possible to do string interpolation with $ in front of the variable:
1
name := 'Bob'
2
println('Hello $name!') // Hello Bob!
Copied!
One can have more complex expressions with interpolation syntax by using ${}:
1
struct User {
2
name string
3
age int
4
}
5
bob := User {
6
name: 'Bob'
7
age: 17
8
}
9
println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17
10
println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false
Copied!

Concatenation

Strings can be concatenated with the + operator.
1
text := 'Hello'
2
concatenated_text := text + ' World!'
3
println(text) // Hello
4
println(text + ' World!') // Hello World!
5
println(concatenated_text) // Hello World!
Copied!
Appending to a string works with concatenation as well as with += operator. Since strings are immutable by default it is only possible to do this if they are declared with mut.
1
mut hello := 'Hello '
2
hello += 'from V!' // appends 'from V!' to the string stored in hello.
3
println(hello) // Hello from V!
Copied!
In V, string data is encoded using UTF-8 and the string itself is a read-only array of bytes. This makes slicing possible, which means we can access single-character literals or slices of a string variable.
1
robert := 'Robert'
2
bert := robert[2..robert.len] // bert
3
rob := robert[0..3] // Rob
4
println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob
Copied!

Notes

When using some_string[start..end] syntax the end is not inclusive.
All operators in V must have values of the same type on both sides. The code below will not compile because age is an int:
1
age := 25
2
println('age = ' + age)
Copied!
We therefore need to convert it to string by using .str() or use string interpolation (preferred):
1
age := 25
2
println('age = ' + age.str()) // age = 25
3
println('age = $age') // age = 25
Copied!
To define character literals use: `` . Raw strings can be defined as prepending r. They are not escaped.
1
hello := 'Hello\nWorld'
2
println(hello) // Hello
3
// World
4
raw_hello := r'Hello\nWorld'
5
println(raw_hello) // Hello\nWorld
Copied!