Dot syntax in match

match i {
  list.len() - 1 => format!("And all for the want of a {}.", list[0]),
  _ => format!("For want of a {} the {} was lost.", list[i], list[i + 1])

how can I do the second line works using dot: list.len() - 1
without use a _ if a == list.len() - 1

This seems like an overuse of match, when if-else will do it easily. That is also an expression that can result in values from each branch.

The more direct answer is that match requires fixed patterns, which can't contain runtime expression like you want. The if guard is the only place for that.


You may be able to avoid using indexing at a higher level. Example on the playground.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.