Structs
Structs in TypeScript vs Rust
Section titled “Structs in TypeScript vs Rust”TypeScript uses class to bundle data and behavior, and interface or object literals for plain data shapes. Rust separates data from behavior: a struct holds the data, and an impl block attaches methods to it. There is no inheritance — composition is the Rust way.
Defining a struct
Section titled “Defining a struct”A struct is like a TypeScript interface that actually holds data:
// TypeScript interface (shape only)interface Point { x: number; y: number; }
// Rust struct (data + can have methods)struct Point { x: f64, y: f64 }Adding methods with impl
Section titled “Adding methods with impl”Methods go in a separate impl block. Methods that read data take &self (immutable reference). Methods that mutate take &mut self. Functions in impl without a self parameter are associated functions — called with :: syntax, used as constructors.
class Point { constructor(public x: number, public y: number) {}
static new(x: number, y: number) { return new Point(x, y); }
distanceFromOrigin(): number { return Math.sqrt(this.x ** 2 + this.y ** 2); }}
const p = Point.new(3, 4);console.log(p.distanceFromOrigin()); // 5struct Point { x: f64, y: f64,}
impl Point { // associated function (constructor) — called with Point::new(...) fn new(x: f64, y: f64) -> Self { Point { x, y } }
// method — called with p.distance_from_origin() fn distance_from_origin(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }}
fn main() { let p = Point::new(3.0, 4.0); println!("{}", p.distance_from_origin()); // 5}Try it
Section titled “Try it”struct Point { x: f64, y: f64,}
impl Point { fn new(x: f64, y: f64) -> Self { Point { x, y } }
fn distance_from_origin(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }}
fn main() { let p = Point::new(3.0, 4.0); println!("distance = {}", p.distance_from_origin());}Compiling…