V Forum

[ log in ]

How to create a function with default parameter?

UnknownAdam777 May 19 08:28
Please, i want to make a function. But i dont know make the default parameter?
Delta456 May 30 08:29
Hey! V doesn't have default parameter but you can do it like this.

struct Foo {
a int = 1
b int
c int = 2
}

fn foo(f Foo) {}

then you can use it like this

foo(b:2) // default value of a and b will be 1
RiordanIX Jun 5 01:17
As Delta456 said, you can define a struct with specific default values, which your function takes as a parameter. V has short-hand notation for functions that only take a single struct: the `foo(b:2)` in the example.

A note on this however: if you are 100% using the default, you must call the function with an 'empty' struct: `foo({})`.
ntrel Jul 7 14:40
> V has short-hand notation for functions that only take a single struct

I found it works for any function with a struct as the last parameter:

struct Config {
n int
def int = 10
}

fn foo(def int, c Config) {
assert c.def == def
}

fn main() {
foo(10, n: 40)
fo
o(40, n: 30, def: 40)
}



Powered by Vorum, open-source blogging/forum software written in V