官术网_书友最值得收藏!

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 }
主站蜘蛛池模板: 万源市| 永年县| 郸城县| 五原县| 恩施市| 寻乌县| 鄂托克前旗| 陇南市| 福海县| 彩票| 扬中市| 蒲城县| 内乡县| 宁乡县| 武汉市| 和硕县| 泾阳县| 武胜县| 云安县| 修文县| 远安县| 麟游县| 枝江市| 绥化市| 宜宾市| 乐昌市| 哈巴河县| 白城市| 行唐县| 罗源县| 石河子市| 法库县| 城口县| 富阳市| 阳高县| 庐江县| 太仓市| 繁峙县| 赣榆县| 宜宾县| 县级市|