How can I loop over an array of strings on v programming language?
For example:
langs := ['python', 'java', 'javascript']
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
V's official documentation claims that it is as fast as C, with the least amount of allocations and an in-built serialization without any run-time reflection.
We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.
Vlang (V) is a statically typed programming language inspired by Rust, Go, Oberon, Swift, Kotlin, and Python. It is open-sourced and claims to be very easy to learn. Based on the V documentation: “Going through this documentation will take you about an hour, and by the end, you will have learned the entire language.”
Method 1: For loop with index
langs := ['python', 'java', 'javascript']
for i, lang in langs {
println('$i) $lang')
}
Method 1 Output:
0) python
1) java
2) javascript
Try method 1 on vlang's playground here
Method 2: For loop without index
langs := ['python', 'java', 'javascript']
for lang in langs {
println(lang)
}
Method 2 Output:
python
java
javascript
Try method 2 on vlang's playground here
Method 3: While loop style iteration using for in V Lang
You can do this too. Following loop is similar to while
loop in other languages.
mut num := 0
langs := ['python', 'java', 'javascript']
for{
if num < langs.len {
println(langs[num])
}
else{
break
}
num++
}
Method 3 Output:
python
java
javascript
Try method 3 on vlang's playground here
Method 4: Looping over elements of an array by accessing its index
langs := ['python', 'java', 'javascript']
mut i := 0
for i < langs.len {
println(langs[i])
i++
}
Method 4 Output:
python
java
javascript
Try method 4 on V lang's playground here
Method 5: Traditional C-Style looping
As suggested by @Astariul in the comments
langs := ['python', 'java', 'javascript']
for i := 0; i < langs.len; i++ {
println(langs[i])
}
Method 5 Output:
python
java
javascript
Try method 5 on V lang's playground here
You can checkout this playlist for more interesting vlang tutorials
V has only one looping construct: for
.
In order to loop over the array langs
, you need to use the for loop.
langs := ['python', 'java', 'javascript']
for lang in langs {
println(lang)
}
The for value in loop is used for going through elements of an array. If an index is required, an alternative form for index, value in
can be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With