rust vector and for
Zhangwuji
Posted on May 21, 2024
1.
Vector is an array it's length can be expended。
//empty Vector
let mut a = Vec::new();
// init with one element at least
let mut a1= vec![1,2,33,44,55];
// the elements inner vec instace must be same type
enum One {
Ha,
String(String),
Number(u64)
}
let mut a1= vec![One::ha,One::String(String::from("你好"))];
so how to traverse a1 it's type is vec;
recommond for in;
enum One {
Ha,
String(String),
Number(u64)
}
let mut a1= vec![One::ha,One::String(String::from("你好"))];
for item in a1 {
}
print!("{:#?}",{a1});
in a1 the control is given to “for”,So after excuted for statement;
a1 was destroied;
you must use &a in order to borrow the reference;like bellow
enum One {
Ha,
String(String),
Number(u64)
}
let mut a1= vec![One::ha,One::String(String::from("你好"))];
for item in &a1 {
}
print!("{:#?}",{a1});
- for statement any Type that implement Iterator trait can be traverse by for; if the value was traverse is not a borrow refrence; like this
let mut hh=Person {
name:String::from("jack")
};
let mut a = vec![ hh];
for item in a{
}
if you want change the element in for statement;
something remember;
Even though a variable is mutable or immutable;
the item is default setted up to immutable;
so if you want item to be settted to mutable;
Just like this;
for mut item in a{
item.name =String::from("lo");
};
or
for mut item in &a{
item.name =String::from("lo");
};
followed situation is not allowed;
for &item in a{
item.name =String::from("lo");
};
why? let me analyse which steps happen?
one: take the element of a out of a;
move the control of element to item;
So & and item are combind into &item which regard as reference of the element。
- a is not a borrow reference; so item'type expect to be the type of element; so this won't work. 2.if a is borrow reference;
for &item in &a{
item.name =String::from("lo");
};
reference a dose't have the control of a.So &a is not allowed to move the control of emenet to item; So this won't work.
one situation will work;
if the type implement copy trait; such as u8, u64..,bool,“char”,
let a = vec![1,2,4,3];
for &item in &a{
};
let a = vec!["s","sa","sad"];
for &item in &a{
let g=item;
};
let a = vec![true];
for &item in &a{
let g=item;
};
remember one strange situation
let mut a =vec![String::from("hello"),String::from("world")];
for item in &mut a {
item*=String::from("12312");
}
item* did not mean control moving. item* mean read from head. item* = String::from("12312") mean write from head.
follow case mean control moving;
let a=*item
Posted on May 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.