Structs & Methods

Defining your own types, impl blocks, &self vs &mut self, derive, and the newtype pattern.

A struct groups named fields into a new type, and an impl block attaches functions and methods to it. Rust has no classes and no inheritance of data; structs plus traits (a later lesson) cover the same ground.

A sensor type

Sensor::new is an associated function (no self), used as a constructor by convention.

in_range(&self) only reads; widen(&mut self) modifies, so it needs a mutable variable...cell.clone() fills the remaining fields from another value (struct update syntax).

Celsius(f64) is a tuple struct: a distinct type, so a Celsius cannot be passed where a Fahrenheit is expected.

Method receivers

let cell = Sensor::new(...); cell.widen(5.0); // cannot borrow as mutable let mut cell = Sensor::new(...); cell.widen(5.0);

Calling a &mut self method needs a mutable binding.

What is the difference between an associated function and a method?

A method takes self (in some form) and is called with value.method(); an associated function has no self and is called with Type::function(), like constructors.