-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLearn_Struct_Trait_And_Impl.rs
More file actions
73 lines (64 loc) · 2.21 KB
/
Learn_Struct_Trait_And_Impl.rs
File metadata and controls
73 lines (64 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// 1. Define a trait named `Bite`
//
// Define a single required method, `fn bite(self: &mut Self)`. We will call this method when we
// want to bite something. Once this trait is defined, you should be able to run the program with
// `cargo run` without any errors.
//
// trait Bite...
trait Bite {
fn bite(self: &mut Self);
}
// 2. Now create a struct named Grapes with a field that tracks how many grapes are left. If you
// need a hint, look at how it was done for Carrot at the bottom of this file (you should probably
// use a different field, though).
//
// #[derive(Debug)] // include this line right before your struct definition
// struct Grapes...
#[derive(Debug)]
struct Grapes {
amount_left: u8,
}
// 3. Implement Bite for Grapes. When you bite a Grapes, subtract 1 from how many grapes are left.
// If you need a hint, look at how it was done for Carrot at the bottom of this file.
//
// impl Bite for...
impl Bite for Grapes {
fn bite(self: &mut Self){
self.amount_left -= 1;
}
}
fn main() {
// Once you finish #1 above, this part should work.
let mut carrot = Carrot { percent_left: 100.0 };
carrot.bite();
println!("I take a bite: {:?}", carrot);
// 4. Uncomment and adjust the code below to match how you defined your
// Grapes struct.
//
let mut grapes = Grapes { amount_left: 100 };
grapes.bite();
println!("Eat a grape: {:?}", grapes);
// function for extra challenge
fn bunny_nibbles<T: Bite>(obj: &mut T){
obj.bite();
}
// Challenge: Uncomment the code below. Create a generic `bunny_nibbles`
// function that:
// - takes a mutable reference to any type that implements Bite
// - calls `.bite()` several times
// Hint: Define the generic type between the function name and open paren:
// fn function_name<T: Bite>(...)
//
bunny_nibbles(&mut carrot);
println!("Bunny nibbles for awhile: {:?}", carrot);
}
#[derive(Debug)] // This enables using the debugging format string "{:?}"
struct Carrot {
percent_left: f32,
}
impl Bite for Carrot {
fn bite(self: &mut Self) {
// Eat 20% of the remaining carrot. It may take awhile to eat it all...
self.percent_left *= 0.8;
}
}