From 67cdcc2e12118becb823e20a40cc2687f2b8425a Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Wed, 27 Mar 2019 15:32:37 -0400 Subject: Started Rust in Action MEAP. --- meap/meap-code/ch3/ch3-defining-files-neatly.rs | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 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 100644 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