HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

Iterating over a slice's values instead of references in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
sliceiteratingoverrustvaluesinsteadreferences

Problem

When looping over a slice of structs, the value I get is a reference (which is fine), however in some cases it's annoying to have to write var as (*var) in many places.

Is there a better way to avoid re-declaring the variable?

fn my_fn(slice: &[MyStruct]) {
    for var in slice {
        let var = *var;  // >` not satisfied
            foo();
        }
    }
}

Solution

You can remove the reference by destructuring in the pattern (old link):

//  |
//  v
for &var in slice {
    other_fn(var);
}


However, this only works for Copy-types! If you have a type that doesn't implement Copy but does implement Clone, you could use the cloned() iterator adapter; see Chris Emerson's answer for more information.

Code Snippets

//  |
//  v
for &var in slice {
    other_fn(var);
}

Context

Stack Overflow Q#40613725, score: 62

Revisions (0)

No revisions yet.