/
basic.rs
91 lines (84 loc) · 3.58 KB
/
basic.rs
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
86
87
88
89
90
91
//! # Basic Usage of the `trait_variable` Macro
//!
//! This file demonstrates the basic usage of the `trait_variable` macro.
/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓trait definition↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
use trait_variable::{trait_var, trait_variable};
trait_variable! {
pub(crate) trait BasicTrait { // feel free to add `pub` when needed
// 1.put the variable fields definition at the TOP of the target trait before any function
x: i32;
pub y: bool;
// 2.the order of the function definition doesn't matter
fn print_x(&self){
println!("x: `{}`", self.x);
}
fn print_y(&self){
println!("y: `{}`", self.y);
}
fn print_all(&self);
}
}
/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑trait definition↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/
/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓struct definition↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
// way1: use the attribute macro to expand the struct (Recommended)
#[trait_var(BasicTrait)]
struct MyStructForBasic {
// feel free to add `pub` when needed
// feel free to add any fields as usual or leave it empty
a: i32,
pub b: String,
}
// way2: use the hidden declarative macro to expand the struct (Not recommended)
// BasicTrait_for_struct! {
// pub struct MyStructForBasic { // feel free to add `pub` when needed
// // feel free to add any fields as usual or leave it empty
// a: i32,
// pub b: String,
// }
// }
/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑struct definition↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/
/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓struct impl↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
// the struct basic implementation
impl MyStructForBasic {
pub fn new(a: i32, b: String, x: i32, y: bool) -> Self {
Self { a, b, x, y }
}
}
// the trait implementation
impl BasicTrait for MyStructForBasic {
fn print_all(&self) {
println!("a: `{}`", self.a);
println!("b: `{}`", self.b);
self.print_x();
println!("y: `{}`", self.y);
}
}
/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑struct impl↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/
/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓anthor struct for test↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
#[trait_var(BasicTrait)]
struct AnthorStruct {
c: i32,
d: bool,
}
/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑anthor struct for test↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/
#[test]
fn test() {
// create a struct instance using the trait_variable macro
let s = MyStructForBasic::new(1, "hello".into(), -2, true);
s.print_all();
assert_eq!(s.a, 1);
assert_eq!(s.b, "hello");
assert_eq!(s.x, -2); // if not in a unit test, then `self.x`` is not accessible, since it is private
assert!(s.y);
// create another struct instance using the trait_variable macro
let s2 = AnthorStruct {
c: 42,
d: true,
x: -2,
y: true,
};
assert_eq!(s2.c, 42);
assert!(s2.d);
assert_eq!(s2.x, -2);
assert!(s2.y);
}