Skip to content

Commit 20b454a

Browse files
committed
added units example
1 parent 8ddc133 commit 20b454a

File tree

3 files changed

+68
-2
lines changed

3 files changed

+68
-2
lines changed

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@ in a controlled repository now.
1515
* `rc`: examples with `RefCell` and `Rc`
1616
* `readline`: example of readline with error handling
1717
* `error`: example of creating a custom error
18-
* `modules`: example of Rust modules
19-
* `point.rs`: example of Rust "methods" and ownership
18+
* `modules`: example of modules
19+
* `point.rs`: example of "methods" and ownership
20+
* `units.rs`: example of newtype and deriving

rc/examples/03-refcell.rs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// https://doc.rust-lang.org/std/cell/
2+
use rc::refcell::Counter;
3+
4+
/// Increment the given counter. Note that this function
5+
/// takes `counter` by immutable reference.
6+
fn update_counter(counter: &Counter) {
7+
counter.incr();
8+
}
9+
10+
fn main() {
11+
let counter = Counter::default();
12+
println!("{}", counter.value());
13+
update_counter(&counter);
14+
println!("{}", counter.value());
15+
println!("{}", counter.incr_value());
16+
}

units.rs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// https://doc.rust-lang.org/stable/rust-by-example/trait/derive.html
2+
3+
// A tuple struct that can be compared
4+
#[derive(PartialEq, PartialOrd)]
5+
struct Centimeters(f64);
6+
7+
// A tuple struct that can be printed
8+
#[derive(Debug)]
9+
struct Inches(i32);
10+
11+
impl Inches {
12+
fn to_centimeters(&self) -> Centimeters {
13+
let &Inches(inches) = self;
14+
15+
Centimeters(inches as f64 * 2.54)
16+
}
17+
}
18+
19+
// A vanilla tuple struct
20+
struct Seconds(i32);
21+
22+
fn main() {
23+
let _one_second = Seconds(1);
24+
25+
// Error! `Seconds` can't be printed, because it doesn't implement the
26+
// `Debug` trait
27+
//println!("One second looks like: {}", _one_second);
28+
// TODO ^ Try uncommenting this line
29+
30+
// Error: `Seconds` can't be compared, because it doesn't implement the
31+
// `PartialEq` trait
32+
//let _this_is_true = _one_second == _one_second;
33+
// TODO ^ Try uncommenting this line
34+
35+
let foot = Inches(12);
36+
37+
println!("One foot === {:?}", foot);
38+
39+
let meter = Centimeters(100.0);
40+
41+
let cmp =
42+
if foot.to_centimeters() < meter {
43+
"smaller"
44+
} else {
45+
"bigger"
46+
};
47+
48+
println!("one foot is {} than one meter", cmp);
49+
}

0 commit comments

Comments
 (0)