An impl block associates methods or trait implementations with a Rust type. It is written separately from the struct or enum definition, because Rust has no class keyword. section 3.3 section 3.6.1
Use an impl block to:
- Define methods that operate on a struct or enum, such as File::read. section 3.3 section 3.5
- Create constructors by convention with methods such as new() and new_with_data(). section 3.3.1
- Implement a trait for a specific type with syntax such as impl Read for File. section 3.6.1
- Keep implementation details private unless items are declared public with pub. section 3.0 section 3.9
Constructing and reading a File
struct File { name: String, data: Vec<u8> } impl File { fn new(name: &str) -> File { File { name: String::from(name), data: Vec::new() } } fn read(self: &File, save_to: &mut Vec<u8>) -> usize { let mut data = self.data.clone(); let length = data.len(); save_to.reserve(length); save_to.append(&mut data); length } } let file = File::new("f3.txt"); section 3.3.1 section 3.3.1
Figure 3.2 Illustrating syntactic differences between Rust and most object oriented languages. Within Rust, methods are defined separately from fields.
Compare Rust's separate type and method blocks with the syntax used by class-oriented languages. section 3.3


