Search…
Variables
In V variables can be declared and initialized with the := operator. Variables can only be declared this way in V, this means all variables have an initial value. The type of a variable is inferred from the value on the right hand side. By default variables in V are immutable.
1
age := 23 // int
2
name := 'Alice' // string
3
is_adult := age > 21 // bool
4
5
println(age_str) // 23
6
println(name) // Alice
7
println(is_adult) // true
Copied!
Note: Variables can only be defined in a function. There are no global variables and no global state in V.
To change the value of a variable, it needs to be mutable. This can be done using the mut keyword when declaring the variable. To assign a new value to a variable use =.
1
mut age := 20 // declare the mutable variable age and assign it to the value 20.
2
println(age) // 20
3
age = 21 // assign a new value to age
4
println(age) // 21
Copied!
Leaving out the mut keyword here would result in an error because the value of an immutable variable cannot be changed.
1
fn main() {
2
age = 20
3
println(age)
4
}
Copied!
The code above would result in an error during compilation because the variable age is not declared,
1
fn main() {
2
mut age := 20 // we declare the mutable variable age and assign it to the value 20.
3
println(age) // 20
4
age := 21 // ERROR
5
}
Copied!
here age := 21 will result in another error while compiling because the variable age is already defined in the scope. It's very simple to remember, just declare value with := and assign value with =.
Like Go, You can also use _ for ignoring values when it is not needed. Usually used in multi return functions.
1
_ := "I don't need this value"
2
println(_) // ERROR: Cannot use `_` as value
Copied!

Naming Rules

The following are the rules which should be kept in mind while naming variables.
  • Name should not contain Uppercase letters like AlphaTest
  • Use underscores as separators like hello_world
  • Name should be descriptive as possible
  • Name should not contain __
  • Name should not contain any space
  • If the name is longer than 11 then it must use _ as separator
These rules are from Snake_Case. V uses Snake Case and prefers it because it is more easy to read, write and understand.

Valid Names

1
boby
2
john_dads
3
myfamily_number
Copied!

Invalid Names

1
IamNotValid
2
new Make
Copied!