V for Go programmers — Variables and Control Structures
Covering more topics in V based on the book “Introducing Go”, today we are gonna cover two chapters variables(chapter 3) and control structures(chapter 4) because both topics are very straightforward and easier to grasp in V.
Variables
Variables in V are pretty simple, and are equal to the Go definition:
my_var := 32
othervar := true
And that’s it, V doesn't have an equivalent for var or for multi assignments.
But what about constants?
Every variable in V is a constant(immutable) by default.
But what if I need to change a value of a variable?
It’s quite easy you just have to use the “mut” keyword:
mut my_var := 32
my_var = 45
And that’s how variables work in V.
Control Structures
Now let’s cover conditional and repetition structures in V and their styles
The loop
To loop things in V we can use the “for” keyword:
languages := ["Elixir", "Go", "Haskell", "JavaScript"]
for lang in languages{
println(lang)
}
To get the index of an element in the loop:
languages := ["Elixir", "Go", "Haskell", "JavaScript"]
for index, lang in languages{
println("${index} => ${lang}")
}
Ranges and loops in V:
for i in 0 .. 5 {
print(i)
}
Equivalent to while loops:
mut i := 0
for i <= 100 {
i+=1
}
Infinite loop:
for {
println("looping")
}
C like for loop:
for i := 0; i < 10; i += 1{
if i == 6 {
continue
}
println(i)
}
If expressions in V are also identical to Go ifs
if 30 < 50 {
println('30 less than 50, crazy math')
} else if 30 > 50{
println('That seems more reasonable')
} else {
println('Wait what?')
}
I also can attribute an if statement to a variable:
num := 32
s := if num % 2 == 0 { 'even' } else { 'odd' }
It´s a match
V doesn't have a switch structure but has something that in my opinion is way better, the match structure:
os := 'windows'
match os {
'darwin' { println('macOS.') }
'linux' { println('Linux.') }
else { println(os) }
}
The match operator consists of a more approachable pattern-matching structure for a language that is not in the functional paradigm.
I also can attribute a match statement to a variable:
number := 2
s := match number {
1 { 'one' }
2 { 'two' }
else { 'many' }
}
Others
V also has other operators like Defer, In, and GoTo, wich will not be covered in this article due to being less used, but I will let the link for the documentation here in case you need it in the future.
Exercises
- Write a program that prints out all the numbers between 1 and 100 that are evenly divisible by 3 (i.e., 3, 6, 9, etc.).
- Write a program that prints the numbers from 1 to 100, but for multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz.” For numbers that are multiples of both three and five, print “FizzBuzz.”(Tip: I have implemented it in another article here in case you need help)
And here we covered two chapters with one article, thank you for reading one more episode in this series and for giving V a chance, hope to see you again. Bye!