summaryrefslogtreecommitdiff
path: root/meap/meap-code/ch3/ch3-defining-files-neatly.rs
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
commit67cdcc2e12118becb823e20a40cc2687f2b8425a (patch)
treeed92c3234b89079e6d4cf36f5e80c5ffa79def48 /meap/meap-code/ch3/ch3-defining-files-neatly.rs
parente25482fca375d318a39c3b54db396b0db6e0b263 (diff)
downloadlearning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz
learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip
Started Rust in Action MEAP.
Diffstat (limited to 'meap/meap-code/ch3/ch3-defining-files-neatly.rs')
-rw-r--r--meap/meap-code/ch3/ch3-defining-files-neatly.rs29
1 files changed, 29 insertions, 0 deletions
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<u8>,
+}
+
+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<T>::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