Variables: Difference between revisions

No edit summary
Line 4,994:
 
=={{header|Vlang}}==
<lang>name := 'Bob'
name := 'Bob'
age := 20
large_number := i64(9999999999)</lang>
</lang>
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.
 
Line 5,008 ⟶ 5,006:
 
'''Mutable variables'''
<lang>mut age := 20
mut age := 20
println(age) // 20
age = 21
println(age) // 21</lang>
</lang>
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.
 
Line 5,020 ⟶ 5,016:
 
The values of multiple variables can be changed in one line. In this way, their values can be swapped without an intermediary variable.
<lang>mut a := 0
mut a := 0
mut b := 1
println('$a, $b') // 0, 1
a, b = b, a
println('$a, $b') // 1, 0</lang>
</lang>
'''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).
<lang>fn main() {
fn main() {
a := 10
if true {
Line 5,036 ⟶ 5,029:
}
// warning: unused variable `a`
}</lang>
}
</lang>
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.
 
338

edits