Impl and Constructors
Lesson 31 of 48 in Coddy's Rust for JavaScript Developers course.
A JavaScript class runs its constructor when you call new, and new always produces an instance, so a constructor that rejects its arguments must throw. Arguments are not checked either: call new Palette() with nothing and this.name is simply undefined. Rust has no special constructor syntax. An associated function such as new is a convention, and its body chooses what to return: a struct, an Option, or a Result when creation needs validation. The examples create a named color preset through a factory. A Rust associated function is called with the type name and a double colon because it has no receiver; an instance method instead takes self in some form. Initialization is explicit, so safe code cannot leave a field unset the way a missing JavaScript argument does. Fields without pub stay private to their module, much like #private fields, so a factory can keep representation choices hidden behind its API.
Complete standalone JavaScript program:
class Palette {
constructor(name) { this.name = name; }
static night() { return new Palette("indigo"); }
}
console.log(Palette.night().name);
console.log(new Palette().name);
JavaScript output:
indigo
undefined
Complete standalone Rust program:
struct Palette { name: &'static str }
impl Palette {
fn night() -> Palette { Palette { name: "indigo" } }
}
fn main() { println!("{}", Palette::night().name); }
Rust output:
indigo
Challenge
EasyImplement 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for JavaScript Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap7Structs and State
Structs and FieldsImpl and ConstructorsMethods and ReceiversEncapsulationComposition and OwnershipReceipt State Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler