Search…
Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
Ideally, you should consider using the single responsibility principle (SOLID) which states that every module or function should have responsibility for a single part of the functionality provided by the software to keep your code maintainable.
Like C and Go, functions cannot be overloaded.
1
fn sum(x, y int) int {
2
return x + y
3
}
4
5
println(sum(77, 33))
Copied!
Note: The type comes after the argument's name.
1
fn full_name(first_name, last_name string) string {
2
return first_name + ' ' + last_name
3
}
4
5
println(full_name("Vitor", "Oliveira"))
Copied!

Variadic Functions

Functions can also be variadic i.e. accept an infinite number of arguments. They are not arrays and cannot be returned.
1
fn foo(test ...string) {
2
for txt in test {
3
println(txt)
4
}
5
}
6
7
foo("V", "is", "the", "best", "lang" , "ever")
Copied!
Output
1
V
2
is
3
the
4
best
5
lang
6
ever
Copied!

Multi-Return Functions

Similar to Go, functions in V can also return multiple and with a different type.
1
fn student(name string, age int) (string, int) {
2
return name, age
3
}
4
5
name1, age1 := student("Tom", 15)
6
println(name1)
7
println(age1)
Copied!
Output
1
Tom, 15
Copied!

High Order Functions

Functions in V can also take in another function as a parameter which is usually needed for something like sort, map, filter, etc.
1
fn square(num int) int {
2
return num * num
3
}
4
5
fn run(value int, op fn(int) int) int {
6
return op(value)
7
}
8
9
println(run(10, square))
Copied!
Output
1
100
Copied!

Exercises

  1. 1.
    Write a V program to find the square of any number using the function.
  2. 2.
    Write a V program to check a given number is even or odd using the function.
  3. 3.
    Write a V program to convert decimal number to binary number using the function.
  4. 4.
    Write a V program to check whether a number is a prime number or not using the function.
  5. 5.
    Write a V program to get the largest element of an array using the function.
Last modified 2yr ago