Menu
CoddyTech

Impl and Constructors

Lesson 31 of 48 in Coddy's Rust for Python Developers course.

Python __init__ initializes an instance after allocation, and a class method can serve as an alternative constructor. Rust has no reserved constructor method: new is a conventional associated function that returns Self or another declared type. It has no self receiver because no existing instance is required. An impl block groups functions and methods for a type without changing its declared fields. Constructors can centralize defaults or validate inputs and return Option or Result. This example chooses a fixed initial mode. The resulting value is then inspected through a shared-reference method; it is not a validated numeric interval.

Python: complete program

class Mode:
    def __init__(self, automatic):
        self.automatic = automatic
    @classmethod
    def manual(cls):
        return cls(False)
mode = Mode.manual()
print(mode.automatic)

Rust: complete program

struct Mode { automatic: bool }
impl Mode {
    fn manual() -> Self { Mode { automatic: false } }
    fn automatic(&self) -> bool { self.automatic }
}
fn main() { println!("{}", Mode::manual().automatic()); }

Rust new does not automatically run when a struct literal is used. Privacy can restrict which construction routes callers have.

challenge icon

Challenge

Easy

Implement span::Span with private endpoints. Span::new(start: i32, end: i32) -> Option<Span> returns None when end < start; otherwise it preserves both endpoints. Span::width(&self) -> i32 returns end - start, so equal endpoints have width zero. Span::contains(&self, point: i32) -> bool includes both endpoints. solve reads complete triples start end point, each integer between -1000 and 1000. Return width:contains for each valid span, using lowercase true or false, or invalid for a reversed span. Join rows with newlines; no triples returns empty.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, span.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod span;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert!(span::Span::new(18, 12).is_none());
let s = span::Span::new(-13, 24).unwrap();
assert_eq!(s.width(), 37);
assert!(s.contains(-13)); assert!(s.contains(24)); assert!(!s.contains(25));
assert_eq!(s.width(), 37);
let z = span::Span::new(-8, -8).unwrap();
assert_eq!(z.width(), 0); assert!(z.contains(-8)); assert!(!z.contains(-9));
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Python Developers

Practice on your own: Online Rust compiler