-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraits_3.cairo
More file actions
85 lines (71 loc) · 1.81 KB
/
traits_3.cairo
File metadata and controls
85 lines (71 loc) · 1.81 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
74
75
76
77
78
79
80
81
82
83
84
85
#[derive(Copy, Drop)]
struct Fish {
noise: felt252,
distance: u32,
}
#[derive(Copy, Drop)]
struct Dog {
noise: felt252,
distance: u32,
}
trait AnimalTrait<T> {
fn new() -> T;
fn make_noise(self: T) -> felt252;
fn get_distance(self: T) -> u32;
}
trait FishTrait {
fn swim(ref self: Fish) -> ();
}
trait DogTrait {
fn walk(ref self: Dog) -> ();
}
impl AnimalFishImpl of AnimalTrait<Fish> {
fn new() -> Fish {
Fish { noise: 'blub', distance: 0 }
}
fn make_noise(self: Fish) -> felt252 {
self.noise
}
fn get_distance(self: Fish) -> u32 {
self.distance
}
}
impl AnimalDogImpl of AnimalTrait<Dog> {
fn new() -> Dog {
Dog { noise: 'woof', distance: 0 }
}
fn make_noise(self: Dog) -> felt252 {
self.noise
}
fn get_distance(self: Dog) -> u32 {
self.distance
}
}
// TODO: implement FishTrait for the type Fish
impl FishImpl of FishTrait {
fn swim(ref self: Fish) -> () {
let Fish { noise, mut distance } = self;
distance += 1;
self = Fish { noise, distance };
}
}
// TODO: implement DogTrait for the type Dog
impl DogImpl of DogTrait {
fn walk(ref self: Dog) -> () {
let Dog { noise, mut distance } = self;
distance += 1;
self = Dog { noise, distance };
}
}
#[test]
fn test_traits3() {
// Don't modify this test!
let mut salmon: Fish = AnimalTrait::new();
salmon.swim();
assert(salmon.make_noise() == 'blub', 'Wrong noise');
assert(salmon.get_distance() == 1, 'Wrong distance');
let mut dog: Dog = AnimalTrait::new();
dog.walk();
assert(dog.make_noise() == 'woof', 'Wrong noise');
assert(dog.get_distance() == 1, 'Wrong distance');
}