Rust Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. In the src/bin folder, create a file called constructor.rs

  2. Add the following code and run it with cargo run --bin constructor:

1  fn main() {
2 // We don't need to care about
3 // the internal structure of NameLength
4 // Instead, we can just call it's constructor
5 let name_length = NameLength::new("John");
6
7 // Prints "The name 'John' is '4' characters long"
8 name_length.print();
9 }
10
11 struct NameLength {
12 name: String,
13 length: usize,
14 }
15
16 impl NameLength {
17 // The user doesn't need to setup length
18 // We do it for him!
19 fn new(name: &str) -> Self {
20 NameLength {
21 length: name.len(),
22 name,
23 }
24 }
25
26 fn print(&self) {
27 println!(
28 "The name '{}' is '{}' characters long",
29 self.name,
30 self.length
31 );
32 }
33 }