Switch
Switch
switch matches a value against arms. Each arm is a pattern, =>, and a block:
switch algorithm {
SortAlgorithm::Insertion => {
this.sort_insertion(compare)
}
SortAlgorithm::Merge => {
this.sort_merge(compare)
}
SortAlgorithm::Quick => {
this.sort_quick(compare)
}
}It is most often used over an enum, where the arms are the variants. Matching on an enum reads better than a chain of comparisons and keeps the variants in one place.
The catch-all arm
_ is the default arm. It matches anything the arms above it did not, standing
in for every remaining case:
switch algorithm {
SortAlgorithm::Merge => {
this.sort_merge(compare)
}
_ => {
this.sort_insertion(compare)
}
}Put it last. Arms are tried in order, so a _ placed above another arm takes
every value before the later one is ever reached.
A catch-all is what lets a switch stay valid as an enum grows: a new variant
lands in _ rather than falling through unhandled. When you would rather be told
about a new variant than silently absorb it, leave the catch-all off and list the
variants instead.