mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-24 13:09:40 +00:00
update repo layout
This commit is contained in:
223
en/src/collections/hashmap.md
Normal file
223
en/src/collections/hashmap.md
Normal file
@ -0,0 +1,223 @@
|
||||
# HashMap
|
||||
Where vectors store values by an integer index, HashMaps store values by key. It is a hash map implemented with quadratic probing and SIMD lookup. By default, `HashMap` uses a hashing algorithm selected to provide resistance against HashDoS attacks.
|
||||
|
||||
The default hashing algorithm is currently `SipHash 1-3`, though this is subject to change at any point in the future. While its performance is very competitive for medium sized keys, other hashing algorithms will outperform it for small keys such as integers as well as large keys such as long strings, though those algorithms will typically not protect against attacks such as HashDoS.
|
||||
|
||||
The hash table implementation is a Rust port of Google’s [SwissTable](https://abseil.io/blog/20180927-swisstables). The original C++ version of SwissTable can be found [here](https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h), and this [CppCon talk](https://www.youtube.com/watch?v=ncHmEUmJZf4) gives an overview of how the algorithm works.
|
||||
|
||||
|
||||
### Basic Operations
|
||||
1. 🌟🌟
|
||||
|
||||
```rust,editbale
|
||||
|
||||
// FILL in the blanks and FIX the erros
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
let mut scores = HashMap::new();
|
||||
scores.insert("Sunface", 98);
|
||||
scores.insert("Daniel", 95);
|
||||
scores.insert("Ashley", 69.0);
|
||||
scores.insert("Katie", "58");
|
||||
|
||||
// get returns a Option<&V>
|
||||
let score = scores.get("Sunface");
|
||||
assert_eq!(score, Some(98));
|
||||
|
||||
if scores.contains_key("Daniel") {
|
||||
// indexing return a value V
|
||||
let score = scores["Daniel"];
|
||||
assert_eq!(score, __);
|
||||
scores.remove("Daniel");
|
||||
}
|
||||
|
||||
assert_eq!(scores.len(), __);
|
||||
|
||||
for (name, score) in scores {
|
||||
println!("The score of {} is {}", name, score)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
let teams = [
|
||||
("Chinese Team", 100),
|
||||
("American Team", 10),
|
||||
("France Team", 50),
|
||||
];
|
||||
|
||||
let mut teams_map1 = HashMap::new();
|
||||
for team in &teams {
|
||||
teams_map1.insert(team.0, team.1);
|
||||
}
|
||||
|
||||
// IMPLEMENT team_map2 in two ways
|
||||
// tips: one of the approaches is to use `collect` method
|
||||
let teams_map2...
|
||||
|
||||
assert_eq!(teams_map1, teams_map2);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
// type inference lets us omit an explicit type signature (which
|
||||
// would be `HashMap<&str, u8>` in this example).
|
||||
let mut player_stats = HashMap::new();
|
||||
|
||||
// insert a key only if it doesn't already exist
|
||||
player_stats.entry("health").or_insert(100);
|
||||
|
||||
assert_eq!(player_stats["health"], __);
|
||||
|
||||
// insert a key using a function that provides a new value only if it
|
||||
// doesn't already exist
|
||||
player_stats.entry("health").or_insert_with(random_stat_buff);
|
||||
assert_eq!(player_stats["health"], __);
|
||||
|
||||
// Ensures a value is in the entry by inserting the default if empty, and returns
|
||||
// a mutable reference to the value in the entry.
|
||||
let health = player_stats.entry("health").or_insert(50);
|
||||
assert_eq!(health, __);
|
||||
*health -= 50;
|
||||
assert_eq!(*health, __);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
|
||||
fn random_stat_buff() -> u8 {
|
||||
// could actually return some random value here - let's just return
|
||||
// some fixed value for now
|
||||
42
|
||||
}
|
||||
```
|
||||
|
||||
### Requirements of HashMap key
|
||||
Any type that implements the `Eq` and `Hash` traits can be a key in `HashMap`. This includes:
|
||||
|
||||
- `bool` (though not very useful since there is only two possible keys)
|
||||
- `int`, `uint`, and all variations thereof
|
||||
- `String` and `&str` (tips: you can have a `HashMap` keyed by `String` and call `.get()` with an `&str`)
|
||||
|
||||
Note that `f32` and `f64` do not implement `Hash`, likely because [floating-point precision](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems) errors would make using them as hashmap keys horribly error-prone.
|
||||
|
||||
All collection classes implement `Eq` and `Hash` if their contained type also respectively implements `Eq` and `Hash`. For example, `Vec<T>` will implement `Hash` if `T`implements `Hash`.
|
||||
|
||||
4. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FIX the errors
|
||||
// Tips: `derive` is usually a good way to implement some common used traits
|
||||
use std::collections::HashMap;
|
||||
|
||||
struct Viking {
|
||||
name: String,
|
||||
country: String,
|
||||
}
|
||||
|
||||
impl Viking {
|
||||
/// Creates a new Viking.
|
||||
fn new(name: &str, country: &str) -> Viking {
|
||||
Viking {
|
||||
name: name.to_string(),
|
||||
country: country.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Use a HashMap to store the vikings' health points.
|
||||
let vikings = HashMap::from([
|
||||
(Viking::new("Einar", "Norway"), 25),
|
||||
(Viking::new("Olaf", "Denmark"), 24),
|
||||
(Viking::new("Harald", "Iceland"), 12),
|
||||
]);
|
||||
|
||||
// Use derived implementation to print the status of the vikings.
|
||||
for (viking, health) in &vikings {
|
||||
println!("{:?} has {} hp", viking, health);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Capacity
|
||||
Like vectors, HashMaps are growable, but HashMaps can also shrink themselves when they have excess space. You can create a `HashMap` with a certain starting capacity using `HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap with a default initial capacity (recommended).
|
||||
|
||||
#### Example
|
||||
```rust,editable
|
||||
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
|
||||
map.insert(1, 2);
|
||||
map.insert(3, 4);
|
||||
// indeed ,the capacity of HashMap is not 100, so we can't compare the equality here.
|
||||
assert!(map.capacity() >= 100);
|
||||
|
||||
// Shrinks the capacity of the map with a lower limit. It will drop
|
||||
// down no lower than the supplied limit while maintaining the internal rules
|
||||
// and possibly leaving some space in accordance with the resize policy.
|
||||
|
||||
map.shrink_to(50);
|
||||
assert!(map.capacity() >= 50);
|
||||
|
||||
// Shrinks the capacity of the map as much as possible. It will drop
|
||||
// down as much as possible while maintaining the internal rules
|
||||
// and possibly leaving some space in accordance with the resize policy.
|
||||
map.shrink_to_fit();
|
||||
assert!(map.capacity() >= 2);
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### Ownership
|
||||
For types that implement the `Copy` trait, like `i32` , the values are copied into `HashMap`. For owned values like `String`, the values will be moved and `HashMap` will be the owner of those values.
|
||||
|
||||
5. 🌟🌟
|
||||
```rust,editable
|
||||
// FIX the errors with least changes
|
||||
// DON'T remove any code line
|
||||
use std::collections::HashMap;
|
||||
fn main() {
|
||||
let v1 = 10;
|
||||
let mut m1 = HashMap::new();
|
||||
m1.insert(v1, v1);
|
||||
println!("v1 is still usable after inserting to hashmap : {}", v1);
|
||||
|
||||
let v2 = "hello".to_string();
|
||||
let mut m2 = HashMap::new();
|
||||
// ownership moved here
|
||||
m2.insert(v2, v1);
|
||||
|
||||
assert_eq!(v2, "hello");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### Third-party Hash libs
|
||||
If the performance of `SipHash 1-3` doesn't meet your requirements, you can find replacements in crates.io or github.com.
|
||||
|
||||
The usage of third-party hash looks like this:
|
||||
```rust
|
||||
use std::hash::BuildHasherDefault;
|
||||
use std::collections::HashMap;
|
||||
// introduce a third party hash function
|
||||
use twox_hash::XxHash64;
|
||||
|
||||
|
||||
let mut hash: HashMap<_, _, BuildHasherDefault<XxHash64>> = Default::default();
|
||||
hash.insert(42, "the answer");
|
||||
assert_eq!(hash.get(&42), Some(&"the answer"));
|
||||
```
|
||||
|
6
en/src/collections/intro.md
Normal file
6
en/src/collections/intro.md
Normal file
@ -0,0 +1,6 @@
|
||||
# Collection Types
|
||||
Learning resources:
|
||||
- English: [Rust Book Chapter 8](https://doc.rust-lang.org/book/ch08-00-common-collections.html)
|
||||
- 简体中文: [Rust语言圣经 - 集合类型](https://course.rs/basic/collections/intro.html)
|
||||
|
||||
|
206
en/src/collections/string.md
Normal file
206
en/src/collections/string.md
Normal file
@ -0,0 +1,206 @@
|
||||
# String
|
||||
`std::string::String` is a UTF-8 encoded, growable string. It is the most common string type we used in daily dev, it also has ownership over the string contents.
|
||||
|
||||
### Basic operations
|
||||
1. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks and FIX errors
|
||||
// 1. Don't use `to_string()`
|
||||
// 2. Dont't add/remove any code line
|
||||
fn main() {
|
||||
let mut s: String = "hello, ";
|
||||
s.push_str("world".to_string());
|
||||
s.push(__);
|
||||
|
||||
move_ownership(s);
|
||||
|
||||
assert_eq!(s, "hello, world!");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
|
||||
fn move_ownership(s: String) {
|
||||
println!("ownership of \"{}\" is moved here!", s)
|
||||
}
|
||||
```
|
||||
|
||||
### String and &str
|
||||
A `String` is stored as a vector of bytes (`Vec<u8>`), but guaranteed to always be a valid UTF-8 sequence. `String` is heap allocated, growable and not null terminated.
|
||||
|
||||
`&str` is a slice (`&[u8]`) that always points to a valid UTF-8 sequence, and can be used to view into a String, just like `&[T]` is a view into `Vec<T>`.
|
||||
|
||||
2. 🌟🌟
|
||||
```rust,editable
|
||||
// FILL in the blanks
|
||||
fn main() {
|
||||
let mut s = String::from("hello, world");
|
||||
|
||||
let slice1: &str = __; // in two ways
|
||||
assert_eq!(slice1, "hello, world");
|
||||
|
||||
let slice2 = __;
|
||||
assert_eq!(slice2, "hello");
|
||||
|
||||
let slice3: __ = __;
|
||||
slice3.push('!');
|
||||
assert_eq!(slice3, "hello, world!");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
3. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// Question: how many heap allocations are happend here ?
|
||||
// Your answer:
|
||||
fn main() {
|
||||
// Create a String type based on `&str`
|
||||
// the type of string literals is `&str`
|
||||
let s: String = String::from("hello, world!");
|
||||
|
||||
// create a slice point to String `s`
|
||||
let slice: &str = &s;
|
||||
|
||||
// create a String type based on the recently created slice
|
||||
let s: String = slice.to_string();
|
||||
|
||||
assert_eq!(s, "hello, world!");
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### UTF-8 & Indexing
|
||||
Strings are always valid UTF-8. This has a few implications:
|
||||
|
||||
- the first of which is that if you need a non-UTF-8 string, consider [OsString](https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html). It is similar, but without the UTF-8 constraint.
|
||||
- The second implication is that you cannot index into a String
|
||||
|
||||
Indexing is intended to be a constant-time operation, but UTF-8 encoding does not allow us to do this. Furthermore, it’s not clear what sort of thing the index should return: a byte, a codepoint, or a grapheme cluster. The bytes and chars methods return iterators over the first two, respectively.
|
||||
|
||||
4. 🌟🌟🌟 You can't use index to access a char in a string, but you can use slice `&s1[start..end]`.
|
||||
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blank and FIX errors
|
||||
fn main() {
|
||||
let s = String::from("hello, 世界");
|
||||
let slice1 = s[0]; //tips: `h` only takes 1 byte in UTF8 format
|
||||
assert_eq!(slice1, "h");
|
||||
|
||||
let slice2 = &s[3..5];// tips: `中` takes 3 bytes in UTF8 format
|
||||
assert_eq!(slice2, "世");
|
||||
|
||||
// iterate all chars in s
|
||||
for (i, c) in s.__ {
|
||||
if i == 7 {
|
||||
assert_eq!(c, '世')
|
||||
}
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### utf8_slice
|
||||
You can use [utf8_slice](https://docs.rs/utf8_slice/1.0.0/utf8_slice/fn.slice.html) to slice UTF8 string, it can index chars instead of bytes.
|
||||
|
||||
**Example**
|
||||
```rust
|
||||
use utf8_slice;
|
||||
fn main() {
|
||||
let s = "The 🚀 goes to the 🌑!";
|
||||
|
||||
let rocket = utf8_slice::slice(s, 4, 5);
|
||||
// Will equal "🚀"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
5. 🌟🌟🌟
|
||||
> Tips: maybe you need `from_utf8` method
|
||||
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks
|
||||
fn main() {
|
||||
let mut s = String::new();
|
||||
__;
|
||||
|
||||
// some bytes, in a vector
|
||||
let v = vec![104, 101, 108, 108, 111];
|
||||
|
||||
// Turn a bytes vector into a String
|
||||
let s1 = __;
|
||||
|
||||
|
||||
assert_eq!(s, s1);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### Representation
|
||||
A String is made up of three components: a pointer to some bytes, a length, and a capacity.
|
||||
|
||||
The pointer points to an internal buffer String uses to store its data. The length is the number of bytes currently stored in the buffer( always stored on the heap ), and the capacity is the size of the buffer in bytes. As such, the length will always be less than or equal to the capacity.
|
||||
|
||||
6. 🌟🌟 If a String has enough capacity, adding elements to it will not re-allocate
|
||||
```rust,editable
|
||||
|
||||
// modify the code below to print out:
|
||||
// 25
|
||||
// 25
|
||||
// 25
|
||||
// Here, there’s no need to allocate more memory inside the loop.
|
||||
fn main() {
|
||||
let mut s = String::new();
|
||||
|
||||
println!("{}", s.capacity());
|
||||
|
||||
for _ in 0..2 {
|
||||
s.push_str("hello");
|
||||
println!("{}", s.capacity());
|
||||
}
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
7. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks
|
||||
use std::mem;
|
||||
|
||||
fn main() {
|
||||
let story = String::from("Rust By Practice");
|
||||
|
||||
// Prevent automatically dropping the String's data
|
||||
let mut story = mem::ManuallyDrop::new(story);
|
||||
|
||||
let ptr = story.__();
|
||||
let len = story.__();
|
||||
let capacity = story.__();
|
||||
|
||||
assert_eq!(16, len);
|
||||
|
||||
// We can re-build a String out of ptr, len, and capacity. This is all
|
||||
// unsafe because we are responsible for making sure the components are
|
||||
// valid:
|
||||
let s = unsafe { String::from_raw_parts(ptr, len, capacity) };
|
||||
|
||||
assert_eq!(*story, s);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Common methods
|
||||
More exercises of String methods can be found [here](../std/String.md).
|
||||
|
||||
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it
|
244
en/src/collections/vector.md
Normal file
244
en/src/collections/vector.md
Normal file
@ -0,0 +1,244 @@
|
||||
# Vector
|
||||
Vectors are re-sizable arrays. Like slices, their size is not known at compile time, but they can grow or shrink at any time.
|
||||
|
||||
### Basic Operations
|
||||
1. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
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!(..) and vec![..] are same macros, so
|
||||
let v = vec!(1, 2, 3);
|
||||
is_vec(v);
|
||||
|
||||
// in code below, v is Vec<[u8; 3]> , not Vec<u8>
|
||||
// USE Vec::new and `for` to rewrite the below code
|
||||
let v1 = vec!(arr);
|
||||
is_vec(v1);
|
||||
|
||||
assert_eq!(v, v1);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
|
||||
fn is_vec(v: Vec<u8>) {}
|
||||
```
|
||||
|
||||
|
||||
|
||||
2. 🌟🌟 a Vec can be extended with `extend` method
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blank
|
||||
fn main() {
|
||||
let mut v1 = Vec::from([1, 2, 4]);
|
||||
v1.pop();
|
||||
v1.push(3);
|
||||
|
||||
let mut v2 = Vec::new();
|
||||
v2.__;
|
||||
|
||||
assert_eq!(v1, v2);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### Turn X Into Vec
|
||||
3. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FILL in the blanks
|
||||
fn main() {
|
||||
// array -> Vec
|
||||
// impl From<[T; N]> for Vec
|
||||
let arr = [1, 2, 3];
|
||||
let v1 = __(arr);
|
||||
let v2: Vec<i32> = arr.__();
|
||||
|
||||
assert_eq!(v1, v2);
|
||||
|
||||
|
||||
// String -> Vec
|
||||
// impl From<String> for Vec
|
||||
let s = "hello".to_string();
|
||||
let v1: Vec<u8> = s.__();
|
||||
|
||||
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::__(s);
|
||||
assert_eq!(v2, v3);
|
||||
|
||||
// Iterators can be collected into vectors
|
||||
let v4: Vec<i32> = [0; 10].into_iter().collect();
|
||||
assert_eq!(v4, vec![0; 10]);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### Indexing
|
||||
4. 🌟🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FIX the error and IMPLEMENT the code
|
||||
fn main() {
|
||||
let mut v = Vec::from([1, 2, 3]);
|
||||
for i in 0..5 {
|
||||
println!("{:?}", v[i])
|
||||
}
|
||||
|
||||
for i in 0..5 {
|
||||
// IMPLEMENT the code here...
|
||||
}
|
||||
|
||||
assert_eq!(v, vec![2, 3, 4, 5, 6]);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Slicing
|
||||
A Vec can be mutable. On the other hand, slices are read-only objects. To get a slice, use `&`.
|
||||
|
||||
In Rust, it’s more common to pass slices as arguments rather than vectors when you just want to provide read access. The same goes for `String` and `&str`.
|
||||
|
||||
5. 🌟🌟
|
||||
```rust,editable
|
||||
|
||||
// FIX the errors
|
||||
fn main() {
|
||||
let mut v = vec![1, 2, 3];
|
||||
|
||||
let slice1 = &v[..];
|
||||
// out of bounds will cause a panic
|
||||
// You must use `v.len` here
|
||||
let slice2 = &v[0..4];
|
||||
|
||||
assert_eq!(slice1, slice2);
|
||||
|
||||
// slice are read only
|
||||
// Note: slice and &Vec are different
|
||||
let vec_ref: &mut Vec<i32> = &mut v;
|
||||
(*vec_ref).push(4);
|
||||
let slice3 = &mut v[0..3];
|
||||
slice3.push(4);
|
||||
|
||||
assert_eq!(slice3, &[1, 2, 3, 4]);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
### Capacity
|
||||
The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector’s length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.
|
||||
|
||||
For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector’s length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use `Vec::with_capacity `whenever possible to specify how big the vector is expected to get.
|
||||
|
||||
6. 🌟🌟
|
||||
```rust,editable
|
||||
// FIX the errors
|
||||
fn main() {
|
||||
let mut vec = Vec::with_capacity(10);
|
||||
|
||||
// The vector contains no items, even though it has capacity for more
|
||||
assert_eq!(vec.len(), __);
|
||||
assert_eq!(vec.capacity(), 10);
|
||||
|
||||
// These are all done without reallocating...
|
||||
for i in 0..10 {
|
||||
vec.push(i);
|
||||
}
|
||||
assert_eq!(vec.len(), __);
|
||||
assert_eq!(vec.capacity(), __);
|
||||
|
||||
// ...but this may make the vector reallocate
|
||||
vec.push(11);
|
||||
assert_eq!(vec.len(), 11);
|
||||
assert!(vec.capacity() >= 11);
|
||||
|
||||
|
||||
// fill in an appropriate value to make the `for` done without reallocating
|
||||
let mut vec = Vec::with_capacity(__);
|
||||
for i in 0..100 {
|
||||
vec.push(i);
|
||||
}
|
||||
|
||||
assert_eq!(vec.len(), __);
|
||||
assert_eq!(vec.capacity(), __);
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
### Store distinct types in Vector
|
||||
The elements in a vector mush be the same type, for example , the code below will cause an error:
|
||||
```rust
|
||||
fn main() {
|
||||
let v = vec![1, 2.0, 3];
|
||||
}
|
||||
```
|
||||
|
||||
But we can use enums or trait objects to store distinct types.
|
||||
|
||||
7. 🌟🌟
|
||||
```rust,editable
|
||||
#[derive(Debug)]
|
||||
enum IpAddr {
|
||||
V4(String),
|
||||
V6(String),
|
||||
}
|
||||
fn main() {
|
||||
// FILL in the blank
|
||||
let v : Vec<IpAddr>= __;
|
||||
|
||||
// Comparing two enums need to derive the PartialEq trait
|
||||
assert_eq!(v[0], IpAddr::V4("127.0.0.1".to_string()));
|
||||
assert_eq!(v[1], IpAddr::V6("::1".to_string()));
|
||||
|
||||
println!("Success!")
|
||||
}
|
||||
```
|
||||
|
||||
8. 🌟🌟
|
||||
```rust,editable
|
||||
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() {
|
||||
// FILL in the blank
|
||||
let v: __= vec![
|
||||
Box::new(V4("127.0.0.1".to_string())),
|
||||
Box::new(V6("::1".to_string())),
|
||||
];
|
||||
|
||||
for ip in v {
|
||||
ip.display();
|
||||
}
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user