Search code examples
crystal-lang

What is the "select when" syntax for?


Experimenting with the language I've found that select is defined in the global scope and its precedence is higher than local variables.

def example(select)
  puts select
end
example 3
# Syntax error in eval:3: unexpected token: end (expecting when, else or end)

So experimenting with select step by step I get this:

select 1 end
# Syntax error in eval:3: unexpected token: end (expecting when, else or end)

and then

select when 1 end
# Syntax error in eval:1: invalid select when expression: must be an assignment or call

then

select when x = 1 end
# Syntax error in eval:1: invalid select when expression: must be an assignment or call

then

select when x
# Syntax error in eval:1: unexpected token: EOF (expecting ',', ';' or '

I'll skip ahead a few steps as you should have an idea of how I've come to my question…

select when x;
else y
end
# Error in line 1: undefined local variable or method 'x_select_action'

and lastly

x_select_action = 4

select when x;
else y
end
# Error in line 3: undefined method 'x_select_action' (If you declared 'x_select_action' in a suffix if, declare it in a regular if for this to work. If the variable was declared in a macro it's not visible outside it)

So there is this keyword in the language which precedes local variables precedence and I don't know what it's for. But apparently it looks for x_select_action when x is given as a when clause. What is this select for and how is it meant to be used?

Searching online I see select defined on Enumerable, Hash, Channel, and Array… but at first glance these don't seem to be it.

Thanks for the help!


Solution

  • It's similar to Go's select: https://tour.golang.org/concurrency/5

    But it still needs some tweaks to be finished, that's why there are no docs about it yet.