The variable’s type is inferred from the value on the right hand side.
To choose a different type, use type conversion:
the expression T(v)
converts the value v
to the
type T
.
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.
For consistency across different code bases, all variable and function names
must use the snake_case
style, as opposed to type names, which must use PascalCase
.
mut age := 20
println(age)
println(age)
Try compiling the program above after removing mut
from the first line.
Note the (important) difference between :=
and =
.
:=
is used for declaring and initializing, =
is used for assigning.
This code will not compile, because the variable age
is not declared.
All variables need to be declared in V.
fn main() {
age := 21
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).
// failcompile nofmt
a := 10
if true {
a := 20 // error: redefinition of `a`
}
// warning: unused variable `a`
Unlike most languages, variable shadowing is not allowed. Declaring a variable with a name that is already used in a parent scope will cause a compilation error.
You can shadow imported modules though, as it is very useful in some situations: