Reputation: 3722
Can Crystal-lang method return multiple values with specific type?
I know that it can be implemented in this way:
def my_method(arg_1 : Int, arg_2 : String) : Tuple
return arg_1, arg_2
end
res_1, res_2 = my_method(1, "1")
but it also work if I do:
result = my_method(1, "1") #=> {1,"2"}
but can I do somethink like in Go-lang
def my_method(arg_1 : Int, arg_2 : String) : Int, String
return arg_1, arg_2
end
???
Thanks!
Upvotes: 4
Views: 981
Reputation: 2926
Crystal methods can only return one value. The way to "return multiple values" is by returning a tuple and then, if you want, immediately unpack it at the call site, like what you did.
If you want to specify the return type you can do:
def my_method(arg_1 : Int, arg_2 : String) : {Int32, String}
return arg_1, arg_2
end
Or (the same, just another syntax):
def my_method(arg_1 : Int, arg_2 : String) : Tuple(Int32, String)
return arg_1, arg_2
end
You can also use a shorter syntax to return multiple values:
def my_method(arg_1 : Int, arg_2 : String)
{arg_1, arg_2}
end
That is, doing return 1, 2
is internally the same as returning the tuple {1, 2}
.
In the end, it doesn't really matter how this is implemented, maybe in Go the function doesn't really return two values but passes pointers or something like that, and then in assembly there aren't even functions, so what matters if you can return multiple things and then get them all at once, somehow.
Upvotes: 7