Replies: 3 comments
-
I think I found a solution to your question. The strings should be rather converted explicitly with import strconv { atoi }
struct MyStruct {}
struct TestStruct {}
fn (t TestStruct) three_args(m MyStruct, arg1 string, arg2 string, arg3 string) ! {
println('${arg1} is ${atoi(arg2)! * atoi(arg3)!}')
}
fn simpleargs(arg1 string, arg2 string) ! {
println('${arg1} is ${atoi(arg2)! * 2}')
}
fn main() {
t := TestStruct{}
m := MyStruct{}
sargs := ['double2', '2']
simpleargs(...sargs)! // expec 'double2 is 4'
args := ['double2', '2', '2']
t.three_args(m, ...args)! // expect 'double2 is 4'
$for method in TestStruct.methods {
if method.name == 'three_args' {
t.$method(m, args)
}
}
} I just imported the required function ( This is the least invasive change to your original example I found to make it work. (Just for completeness: I formatted my solution with |
Beta Was this translation helpful? Give feedback.
-
Second approach without struct MyStruct {}
struct TestStruct {}
fn (t TestStruct) three_args(m MyStruct, arg1 string, arg2 string, arg3 string) {
println('${arg1} is ${arg2.int() * arg3.int()}')
}
fn simpleargs(arg1 string, arg2 string) {
println('${arg1} is ${arg2.int() * 2}')
}
fn main() {
t := TestStruct{}
m := MyStruct{}
sargs := ['double2', '2']
simpleargs(...sargs) // expec 'double2 is 4'
args := ['double2', '2', '2']
t.three_args(m, ...args) // expect 'double2 is 4'
$for method in TestStruct.methods {
if method.name == 'three_args' {
t.$method(m, args)
}
}
} Here, you would need to call the I think this option is somehow better than my previous suggestion as you do not need to import a function from the standard library and you do not need to care about error values. |
Beta Was this translation helpful? Give feedback.
-
No, the problem is that the function accepts individual arguments, but a variable number are being passed. When a variable number of arguments are passed, they are passed as an array. If you want to pass a variable number of arguments, make the function accept a variable number of arguments, so the array is handled properly. See https://github.com/vlang/v/blob/master/doc/docs.md#variable-number-of-arguments |
Beta Was this translation helpful? Give feedback.
-
printed result:
it seems only compile time is as expected when the args are array. how could i get the same result in others?
Beta Was this translation helpful? Give feedback.
All reactions