Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

rust - What's the idiomatic way to copy from a primitive type reference by value?

Consider the following snippet:

fn example(current_items: Vec<usize>, mut all_items: Vec<i32>) {
    for i in current_items.iter() {
        let mut result = all_items.get_mut(i);
    }
}

The compiler is complaining about i being &mut usize instead of usize:

error[E0277]: the trait bound `&usize: std::slice::SliceIndex<[()]>` is not satisfied
 --> src/lib.rs:3:36
  |
3 |         let mut result = all_items.get_mut(i);
  |                                    ^^^^^^^ slice indices are of type `usize` or ranges of `usize`
  |
  = help: the trait `std::slice::SliceIndex<[()]>` is not implemented for `&usize`

I've dug through the docs but the only way I see to satisfy the compiler is i.clone().

I'm definitely missing something obvious here. What's the idiomatic way to copy from primitive type reference by value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

iter() on Vec<T> returns an iterator implementing Iterator<&T>, that is, this iterator will yield references into the vector. This is the most general behavior which allows convenient usage with non-copyable types.

However, primitive types (actually, any types which implement Copy trait) will be copied upon dereference anyway, so you just need this:

for i in current_items.iter() {
    let mut result = all_items.get_mut(*i);
}

Alternatively, you can use reference destructuring pattern:

for &i in current_items.iter() {
    let mut result = all_items.get_mut(i);
}

Now i is usize automatically and you don't need to dereference it manually.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...