Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

collections/vector #214

giscus[bot] bot announced in Book Comments
Apr 16, 2022 · 23 comments · 5 replies
Discussion options

collections/vector

Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.

https://zh.practice.rs/collections/vector.html

You must be logged in to vote

Replies: 23 comments 5 replies

Comment options

 v2.extend(v1.iter());
You must be logged in to vote
1 reply
Comment options

v2.extend(&v1);

Comment options

好多都没学过 ,我不知道怎么做

You must be logged in to vote
2 replies
Comment options

+1

Comment options

+1

Comment options

在练中学,在学中练

You must be logged in to vote
0 replies
Comment options

Done.

You must be logged in to vote
0 replies
Comment options

2022年12月6日 发现 solution 和题目对不上,这边补充下第三题的答案(只能保证可以跑,仅供参考)

// 填空
fn main() {
 // array -> Vec
 // impl From<[T; N]> for Vec
 let arr = [1, 2, 3];
 let v1 = Vec::from(arr);
 let v2: Vec<i32> = arr.into();
 
 assert_eq!(v1, v2);
 
 
 // String -> Vec
 // impl From<String> for Vec
 let s = "hello".to_string();
 let v1: Vec<u8> = s.into();
 let s = "hello".to_string();
 let v2 = s.into_bytes();
 assert_eq!(v1, v2);
 // impl<'_> From<&'_ str> for Vec
 let s = "hello";
 let v3 = Vec::from(s);
 assert_eq!(v2, v3);
 // 迭代器 Iterators 可以通过 collect 变成 Vec
 let v4: Vec<i32> = [0; 10].iter().map(|x| *x).collect();
 assert_eq!(v4, vec![0; 10]);
 println!("Success!")
 }
You must be logged in to vote
1 reply
Comment options

第五题

// 修复错误
fn main() {
 let mut v = vec![1, 2, 3];
 let slice1 = &v[..];
 // 越界访问将导致 panic.
 // 修改时必须使用 `v.len`
 let slice2 = &v[0..v.len()];
 
 assert_eq!(slice1, slice2);
 
 // 切片是只读的
 // 注意:切片和 `&Vec` 是不同的类型,后者仅仅是 `Vec` 的引用,并可以通过解引用直接获取 `Vec`
 let vec_ref: &mut Vec<i32> = &mut v;
 (*vec_ref).push(4);
 let mut slice3: Vec<i32> = Vec::from(&v[..3]);
 slice3.push(4);
 assert_eq!(slice3, &[1, 2, 3, 4]);
 println!("Success!")
}
Comment options

mark

You must be logged in to vote
0 replies
Comment options

第四题我的做法。忘了用if let了,会比match更简洁。

fn main() {
 let mut v = Vec::from([1, 2, 3]);
 for i in 0..5 {
 match v.get(i)
 {
 Some(num)=>{
 println!("{:?}", num);
 v[i]=num+1;
 },
 None=>v.push(i+2)
 }
 
 }
 assert_eq!(v, vec![2, 3, 4, 5, 6]);
 println!("Success!")
}`
You must be logged in to vote
1 reply
Comment options

fn main() {
 let mut v = Vec::from([1, 2, 3]);
 for i in 0..5 {
 if let Some(num) = v.get(i) {
 println!("{:?}", num);
 v[i] = num + 1;
 } else {
 v.push(i + 2)
 }
 }
 assert_eq!(v, vec![2, 3, 4, 5, 6]);
 println!("Success!")
}
Comment options

lala

You must be logged in to vote
0 replies
Comment options

1、回顾一下对于Vec的遍历,以及其所有权

fn main() {
 let arr: [u8; 3] = [1, 2, 3];
 
 let v = Vec::from(arr);
 is_vec(v.clone());
 let v = vec![1, 2, 3];
 is_vec(v.clone());
 // vec!(..) 和 vec![..] 是同样的宏,宏可以使用 []、()、{}三种形式,因此...
 let v = vec!(1, 2, 3);
 is_vec(v.clone());
 
 // ...在下面的代码中, v 是 Vec<[u8; 3]> , 而不是 Vec<u8>
 // 使用 Vec::new 和 `for` 来重写下面这段代码
 let mut v1=Vec::new();
 for a in arr{
 v1.push(a);
 }
 is_vec(v1.clone());
 
 assert_eq!(v, v1);
 println!("Success!")
}
fn is_vec(v: Vec<u8>) {}

2、Vec可以用extend来进行拓展

fn main() {
 let mut v1 = Vec::from([1, 2, 4]);
 v1.pop();
 v1.push(3);
 
 let mut v2 = Vec::new();
 v2.extend(v1.clone());//这里不clone的话会导致v1失去所有权
 assert_eq!(v1, v2);
 println!("Success!")
}

3、array可以通过.into()变成Vec,或者使用Vec::from()进行转换;Iterator可以通过collect变成 Vec

fn main() {
 // array -> Vec
 // impl From<[T; N]> for Vec
 let arr = [1, 2, 3];
 let v1 = Vec::from(arr);
 let v2: Vec<i32> = arr.into();
 
 assert_eq!(v1, v2);
 // String -> Vec
 // impl From<String> for Vec
 let s = "hello".to_string();
 let v1: Vec<u8> = s.into();
 let s = "hello".to_string();
 let v2 = s.into_bytes();
 assert_eq!(v1, v2);
 // impl<'_> From<&'_ str> for Vec
 let s = "hello";
 let v3 = Vec::from(s);
 assert_eq!(v2, v3);
 // 迭代器 Iterators 可以通过 collect 变成 Vec
 let v4: Vec<i32> = [0; 10].into_iter().collect();
 assert_eq!(v4, vec![0; 10]);
 println!("Success!")
 }

4、索引

fn main() {
 let mut v = Vec::from([1, 2, 3]);
 for i in 0..3 {
 println!("{:?}", v[i])
 }
 for i in 0..5 {
 // 实现这里的代码...
 if i<=2{
 v[i]+=1;
 }else{
 v.push(i+2);
 }
 }
 assert_eq!(v, vec![2, 3, 4, 5, 6]);
 println!("Success!")
}

5、Vec中的切片

fn main() {
 let mut v = vec![1, 2, 3];
 let slice1 = &v[..];
 // 越界访问将导致 panic.
 // 修改时必须使用 `v.len`
 let slice2 = &v[0..v.len()];
 
 assert_eq!(slice1, slice2);
 
 // 切片是只读的
 // 注意:切片和 `&Vec` 是不同的类型,后者仅仅是 `Vec` 的引用,并可以通过解引用直接获取 `Vec`
 let vec_ref: &mut Vec<i32> = &mut v;
 (*vec_ref).push(4);
 let slice3 = &vec_ref[0..4];
 //slice3.push(4);
 assert_eq!(slice3, &[1, 2, 3, 4]);
 println!("Success!")
}

6、lencapacity的区别

fn main() {
 let mut vec = Vec::with_capacity(10);
 assert_eq!(vec.len(), 0);
 assert_eq!(vec.capacity(), 10);
 // 由于提前设置了足够的容量,这里的循环不会造成任何内存分配...
 for i in 0..10 {
 vec.push(i);
 }
 assert_eq!(vec.len(), 10);
 assert_eq!(vec.capacity(), 10);
 // ...但是下面的代码会造成新的内存分配
 vec.push(11);
 assert_eq!(vec.len(), 11);
 assert!(vec.capacity() >= 11);
 // 填写一个合适的值,在 `for` 循环运行的过程中,不会造成任何内存分配
 let mut vec = Vec::with_capacity(100);
 for i in 0..100 {
 vec.push(i);
 }
 assert_eq!(vec.len(),100);
 assert_eq!(vec.capacity(), 100);
 
 println!("Success!")
}

7、用枚举对象在Vec中存储不同的类型

#[derive(Debug,PartialEq)]//注意此处需要实现PartialEq
enum IpAddr {
 V4(String),
 V6(String),
}
fn main() {
 // 填空
 let v : Vec<IpAddr>= Vec::from([
 IpAddr::V4("127.0.0.1".to_string()),
 IpAddr::V6("::1".to_string())
 ]);
 
 // 枚举的比较需要派生 PartialEq 特征
 assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string()));
 assert_eq!(v[1], IpAddr::V6("::1".to_string()));
 println!("Success!")
}

8、实现同一个特征的可以用Box封装起来,然后作为同一个Vec元素

trait IpAddr {
 fn display(&self);
}
struct V4(String);
impl IpAddr for V4 {
 fn display(&self) {
 println!("ipv4: {:?}",self.0)
 }
}
struct V6(String);
impl IpAddr for V6 {
 fn display(&self) {
 println!("ipv6: {:?}",self.0)
 }
}
fn main() {
 // 填空
 let v: Vec<Box<dyn IpAddr>>= vec![
 Box::new(V4("127.0.0.1".to_string())),
 Box::new(V6("::1".to_string())),
 ];
 for ip in v {
 ip.display();
 }
}
You must be logged in to vote
0 replies
Comment options

done

You must be logged in to vote
0 replies
Comment options

7好阴哦

You must be logged in to vote
0 replies
Comment options

到这期确实变难了不少。

You must be logged in to vote
0 replies
Comment options

let v4: Vec<i32> = [0; 10].into_iter().collect();

This will produce error:

value of type `Vec<i32>` cannot be built from `std::iter::Iterator<Item=&{integer}>`

Solutions:

let v4: Vec<i32> = [0; 10].iter().copied().collect(); -> https://stackoverflow.com/a/64200786

Or:

let v4: Vec<i32> = IntoIterator::into_iter([0; 10]).collect();

You must be logged in to vote
0 replies
Comment options

down

You must be logged in to vote
0 replies
Comment options

  • done
You must be logged in to vote
0 replies
Comment options

mark 11.2 5

You must be logged in to vote
0 replies
Comment options

done~~~

You must be logged in to vote
0 replies
Comment options

mark finished

You must be logged in to vote
0 replies
Comment options

难起来了

You must be logged in to vote
0 replies
Comment options

Day 9
Done✅

You must be logged in to vote
0 replies
Comment options

第一题

fn main() {
 let arr: [u8; 3] = [1, 2, 3];
 let v = Vec::from(arr);
 is_vec(&v);
 let v = vec![1, 2, 3];
 is_vec(&v);
 // vec!(..) 和 vec![..] 是同样的宏,宏可以使用 []、()、{}三种形式,因此...
 let v = vec!(1, 2, 3);
 is_vec(&v);
 // ...在下面的代码中, v 是 Vec<[u8; 3]> , 而不是 Vec<u8>
 // 使用 Vec::new 和 `for` 来重写下面这段代码
 // let v1 = vec!(arr);
 let mut v1 = Vec::new();
 for i in &arr {
 v1.push(*i);
 }
 is_vec(&v1);
 assert_eq!(v, v1);
 println!("Success!")
}
fn is_vec(v: &Vec<u8>) {}

第二题

// 填空
fn main() {
 let mut v1 = Vec::from([1, 2, 4]);
 v1.pop();
 v1.push(3);
 let mut v2 = Vec::new();
 v2.extend([1,2,3]);
 assert_eq!(v1, v2);
 println!("Success!")
}

第三题

// 填空
fn main() {
 // array -> Vec
 // impl From<[T; N]> for Vec
 let arr = [1, 2, 3];
 let v1 = Vec::from(arr);
 let v2: Vec<i32> = arr.to_vec();
 assert_eq!(v1, v2);
 // String -> Vec
 // impl From<String> for Vec
 let s = "hello".to_string();
 let v1: Vec<u8> = s.into();
 let s = "hello".to_string();
 let v2 = s.into_bytes();
 assert_eq!(v1, v2);
 // impl<'_> From<&'_ str> for Vec
 let s = "hello";
 let v3 = Vec::from(s);
 assert_eq!(v2, v3);
 // 迭代器 Iterators 可以通过 collect 变成 Vec
 let v4: Vec<i32> = [0; 10].into_iter().collect();
 assert_eq!(v4, vec![0; 10]);
 println!("Success!")
}

第四题

// 修复错误并实现缺失的代码
fn main() {
 let mut v = Vec::from([1, 2, 3]);
 for i in 0..3 {
 println!("{:?}", v[i])
 }
 v.clear();
 for i in 2..7 {
 // 实现这里的代码...
 v.push(i);
 }
 assert_eq!(v, vec![2, 3, 4, 5, 6]);
 println!("Success!")
}

第五题

// 修复错误
fn main() {
 let mut v = vec![1, 2, 3];
 let slice1 = &v[..];
 // 越界访问将导致 panic.
 // 修改时必须使用 `v.len`
 let slice2 = &v[0..v.len()];
 assert_eq!(slice1, slice2);
 // 切片是只读的
 // 注意:切片和 `&Vec` 是不同的类型,后者仅仅是 `Vec` 的引用,并可以通过解引用直接获取 `Vec`
 let vec_ref: &mut Vec<i32> = &mut v;
 (*vec_ref).push(4);
 let slice3 = &mut Vec::from(&v[0..3]);
 slice3.push(4);
 assert_eq!(slice3, &[1, 2, 3, 4]);
 println!("Success!")
}

第六题

// 修复错误
fn main() {
 let mut vec = Vec::with_capacity(10);
 assert_eq!(vec.len(), 0);
 assert_eq!(vec.capacity(), 10);
 // 由于提前设置了足够的容量,这里的循环不会造成任何内存分配...
 for i in 0..10 {
 vec.push(i);
 }
 assert_eq!(vec.len(), 10);
 assert_eq!(vec.capacity(), 10);
 // ...但是下面的代码会造成新的内存分配
 vec.push(11);
 assert_eq!(vec.len(), 11);
 assert!(vec.capacity() >= 11);
 // 填写一个合适的值,在 `for` 循环运行的过程中,不会造成任何内存分配
 let mut vec = Vec::with_capacity(101);
 for i in 0..100 {
 vec.push(i);
 }
 assert_eq!(vec.len(), 100);
 assert_eq!(vec.capacity(), 101);
 println!("Success!")
}

第七题

#[derive(Debug, PartialEq)]
enum IpAddr {
 V4(String),
 V6(String),
}
fn main() {
 // 填空
 let v : Vec<IpAddr>= vec![
 IpAddr::V4("127.0.0.1".to_string()),
 IpAddr::V6("::1".to_string()),
 ];
 // 枚举的比较需要派生 PartialEq 特征
 assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string()));
 assert_eq!(v[1], IpAddr::V6("::1".to_string()));
 println!("Success!")
}

第八题

trait IpAddr {
 fn display(&self);
}
struct V4(String);
impl IpAddr for V4 {
 fn display(&self) {
 println!("ipv4: {:?}",self.0)
 }
}
struct V6(String);
impl IpAddr for V6 {
 fn display(&self) {
 println!("ipv6: {:?}",self.0)
 }
}
fn main() {
 // 填空
 let v: Vec<Box<dyn IpAddr>>= vec![
 Box::new(V4("127.0.0.1".to_string())),
 Box::new(V6("::1".to_string())),
 ];
 for ip in v {
 ip.display();
 }
}
You must be logged in to vote
0 replies
Comment options

done

You must be logged in to vote
0 replies
Comment options

done

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /