From 7e8ee5ed9cad6484e9f13f81731b102ced58402e Mon Sep 17 00:00:00 2001 From: Adam Carpenter Date: Tue, 9 Jul 2019 15:14:04 -0400 Subject: Init. --- meap/meap-code/ch3/ch3-defining-files-neatly.rs | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100755 meap/meap-code/ch3/ch3-defining-files-neatly.rs (limited to 'meap/meap-code/ch3/ch3-defining-files-neatly.rs') diff --git a/meap/meap-code/ch3/ch3-defining-files-neatly.rs b/meap/meap-code/ch3/ch3-defining-files-neatly.rs new file mode 100755 index 0000000..2025f72 --- /dev/null +++ b/meap/meap-code/ch3/ch3-defining-files-neatly.rs @@ -0,0 +1,29 @@ +#[derive(Debug)] +struct File { + name: String, + data: Vec, +} + +impl File { + fn new(name: &str) -> File { // <1> As `File::new()` is a completely normal function--rather than something blessed by the language--we need to tell Rust that it will be returning a `File` from this function + File { // <2> + name: String::from(name), // <2> `File::new()` does little more than encapsulate the object creation syntax + data: Vec::new(), // <2> + } + } + + // fn len(&self) -> usize { // <3> `File::len()` takes an implicit argument `self`. You'll notice that there is no explicit argument provided on line 25. + // self.data.len() // <4> `usize` is the type returned by `Vec::len()`, which is sent directly through to the caller + // } +} + +fn main() { + let f3 = File::new("f3.txt"); + + let f3_name = &f3.name; // <5> Fields are private by default, but can be accessed within the module that defines the struct. The module system is discussed further on in the chapter. + //let f3_length = f3.len(); + let f3_length = f3.data.len(); + + println!("{:?}", f3); + println!("{} is {} bytes long", f3_name, f3_length); +} \ No newline at end of file -- cgit v1.2.3