Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Moving a field in elements of a vector that is owned by callee
How does one move (instead of clone) one field in each element of a vector to a new vector ?
Here is an example of what I am trying to do:
// StringInfo
#[derive(Debug, Clone)]
struct StringInfo {
index : usize ,
value : String ,
}
//
// This method clones strings that will be dropped when it returns.
fn vec_string_info_clone( vec_string : Vec<String> ) -> Vec<StringInfo>
{ let mut vec_string_info : Vec<StringInfo> = Vec::new();
for i in 0 .. vec_string.len() {
vec_string_info.push( StringInfo{ index : i, value : vec_string[i].clone() } );
}
vec_string_info
}
//
// This method does not clone the strings but
// it returns the vector in the reverse of the desired order.
fn vec_string_info_pop( mut vec_string : Vec<String> ) -> Vec<StringInfo>
{ let mut vec_string_info : Vec<StringInfo> = Vec::new();
let len = vec_string.len();
for i in 0 .. len {
let string = vec_string.pop().unwrap();
vec_string_info.push( StringInfo{ index : len - i - 1, value : string } );
}
vec_string_info
}
fn main() {
//
let vec_string = vec![ "zero".to_string(), "one".to_string() ];
let vec_string_info = vec_string_info_clone( vec_string );
println!( "{:?}", vec_string_info );
//
let vec_string = vec![ "zero".to_string(), "one".to_string() ];
let vec_string_info = vec_string_info_pop( vec_string );
println!( "{:?}", vec_string_info );
}
3 posts - 3 participants
🏷️ Rust_feed