Let-Match pattern for Mutable Tuples?


#1

I’m writing some code to traverse a series of edges in a directed graph, but I need to initialize two variables before I begin. Since I need to set two variables simultaneously and mutably, ideally I’d like to write the code like this:

let mut (prev_node, curr_node) = match head_node {
Some(node) => (node, other_nodes[0]),
None => (other_nodes[0], other_nodes[1]),
};

But this doesn’t compile.

While the same code with a non-mutable tuple works (but obviously is not usable for my subsequent loop that traverses the graph).

let (prev_node, curr_node) = match head_node {
Some(node) => (node, other_nodes[0]),
None => (other_nodes[0], other_nodes[1]),
};

…as does a mutable “packed” tuple as a single variable, but this makes the downstream code messier with tuple-indexing instead of named variables.

let mut (prev_node, curr_node) = match head_node {
Some(node) => (node, other_nodes[0]),
None => (other_nodes[0], other_nodes[1]),
};

Is this intended behavior of the compiler, and if so - why?


#2
let (mut prev_node, mut curr_node) = match head_node {
    Some(node) => (node, other_nodes[0]),
    None       => (other_nodes[0], other_nodes[1]),
};

works. (note that the mut is just before the variable name, not before the tuple)


#3

Perfect - this is exactly what I needed. Thanks bjorn