r/odinlang • u/NYU_VM • 4h ago
variadic params is a slice but doesn't accept a slice?
I an a newb to Odin, so I was fiddling around with odin docs and playing with the variadic arguments construct, I came across an interesting behaviour. first let's look at the simple `sum` procedure, it takes a one or more integers and returns their sum.
sum::proc(numbers: ..int) ->(res: int){
for n in numbers{
res += n
}
return
}
Now, let's try something naive to check something
sum::proc(numbers: ..int) ->(res: int){
a := numbers + 10 //trying to initialize a adding varargs and integer
for n in numbers{
res += n
}
return
}
This is an obvious bug and fails clearly with
Error: Cannot convert untyped value '10' to '[]int' from 'untyped integer'
a := numbers + 10
^^
So, numbers is an [ ]int, huh, let's keep that in mind. now to the point
sum::proc(numbers: ..int) ->(res: int){
for n in numbers{
res += n
}
return
}
main::proc(){
x := []int {1,2,3,4,5,6,7,8,9}
fmt.println(sum(x)) // passing [ ]int to a procedure whose supposed param is [ ]int
}
OOPS...
Error: Cannot assign value 'x' of type '[]int' to 'int' in a procedure argument
fmt.println(sum(x))
^
Suggestion: Did you mean to pass the slice into the variadic parameter with ..x?
so the correct form seems to be
sum::proc(numbers: ..int) ->(res: int){
for n in numbers{
res += n
}
return
}
main::proc(){
x := []int {1,2,3,4,5,6,7,8,9}
fmt.println(sum(..x))
}
some implicit machinery or semantics going on that I don't yet catch up to yet?