Object-oriented programming
Axle is class-based. A class has one base class, an explicit constructor and an
optional drop() destructor. Behaviour that several unrelated types share is
written as a trait, a contract a class opts into.
Two rules decide how a call is resolved, and they are the thing to hold in your head:
| Receiver’s declared type | How a method call is resolved |
|---|---|
a class (Point, Circle) | statically, at compile time, on the declared type |
a trait or dyn Trait | dynamically, at run time, from the instance’s concrete type |
The canonical class header is class Foo : Base, Trait: one base class and any
number of traits in a single : list. That list is the only supertype syntax.
Generics are monomorphised, so each instantiation is compiled for its own
element types, though you write them like ordinary generic types.
A class
class Point {
x : f64;
y : f64;
constructor(x : f64, y : f64) {
self.x = x;
self.y = y;
}
pub fn distanceTo(self, other : Point) : f64 {
let dx : f64 = self.x - other.x;
let dy : f64 = self.y - other.y;
return (dx * dx + dy * dy).sqrt();
}
}
fn main() : i32 {
let a : Point = new Point(0.0, 0.0);
let b : Point = new Point(3.0, 4.0);
let d : f64 = a.distanceTo(b); // 5.0
return d.truncToInt() as i32;
} Notes:
- Fields are listed first, separated by semicolons.
constructor(...)is the one initialiser name. A class may declare several;new C(args)picks one by argument count, then by argument type, and two candidates that accept the same argument are refused as E0774.- An instance method names its receiver as its first parameter:
self,mut selforown self. Constructors receive it implicitly. The body refers to the instance throughself. - Methods are called with
.. There is noobj->methodform.
Inheritance
use std::numeric::math;
class Shape {
name : string;
constructor(name : string) {
self.name = name;
}
pub fn describe(self) : string {
return self.name;
}
}
class Circle : Shape {
radius : f64;
constructor(radius : f64) {
super("Circle");
self.radius = radius;
}
pub fn area(self) : f64 {
return math::pi() * self.radius * self.radius;
}
}
class Square : Shape {
side : f64;
constructor(side : f64) {
super("Square");
self.side = side;
}
pub fn area(self) : f64 {
return self.side * self.side;
}
} The hierarchy reads like this. Each arrow points from a subclass to its base:
Shape
(name, describe)
▲ ▲
│ │
Circle Square
(radius, (side,
area) area) - The base is the first entry of the
:list. super(...)calls the base constructor. Call it first in a derived constructor. Skipping it runs the base’s zero-argument constructor; a base with none to name makes the omission E0777.- A derived method with the same signature replaces the base’s, for receivers
of the derived type:
circle.area()findsCircle.area. - A value held as
Shapesees onlyShape’s methods. A base method that callsself.area()runs the base version.
There is no virtual dispatch through a base-typed class variable. To reach
an override, narrow the binding with an is test (see Runtime type tests), or model the
contract as a trait, which dispatches dynamically.
Single inheritance only
A class has one base. Multiple inheritance is not supported. Use traits for capabilities that cut across hierarchies.
Inherited fields come first
class A {
pub x : i32;
constructor(x : i32) {
self.x = x;
}
}
class B : A {
pub y : i32;
constructor(x : i32, y : i32) {
super(x);
self.y = y;
}
}
class C : B {
pub z : i32;
constructor(x : i32, y : i32, z : i32) {
super(x, y);
self.z = z;
}
}
fn main() : i32 {
let c : C = new C(1, 2, 3);
return c.x + c.y + c.z; // 6
} The layout of C is [x, y, z]: base fields come first, in declaration
order. Each field sits at a fixed offset, so an upcast (viewing a C as a B or an A) costs nothing.
Traits
A trait is the named capability contract. A class opts in with a : Trait clause. A receiver typed as a trait dispatches at run time from the instance’s
concrete type, through a type tag stored in each instance.
Basic contract
trait Reader {
fn read(self) : i32;
}
class Mem : Reader {
v : i32;
constructor(v : i32) {
self.v = v;
}
pub fn read(self) : i32 {
return self.v;
}
}
class Const : Reader {
constructor() {}
pub fn read(self) : i32 {
return 12;
}
}
fn use_reader(r : Reader) : i32 { // receiver held *as* the trait
return r.read(); // dispatched at run time from r's type
}
fn main() : i32 {
let m : Mem = new Mem(30);
let c : Const = new Const();
return use_reader(m) + use_reader(c); // 30 + 12 = 42
} use_reader(r : Reader)
│ r.read()
▼
┌───────────────┐
│ type tag │──── Mem ──▶ Mem.read (returns v)
│ (in instance) │──── Const ──▶ Const.read (returns 12)
└───────────────┘ - The compiler checks conformance. A class that names a trait but omits one
of its methods is E0026. A method whose signature does not match the
contract is E0029; the check walks the base chain, so a drifting override
is caught too. A
staticmethod never satisfies an instance contract, since it has no receiver, so the contract method reads as missing (E0026). - Calling a method through a trait-typed receiver when the trait does not declare it is E0030.
- A trait may name super-traits, as in
trait Reader : Closeable. A sub-trait value flows into a super-trait slot: aReaderis accepted where aCloseableis expected. - Each instance carries a hidden type tag, placed in a leading run-time type
header. A call through a trait-typed receiver reads the tag and selects the
concrete class’s body.
MemandConstflowing into the sameReaderslot therefore run differentreadbodies. - A trait method’s declared error set is part of its contract. A checked
exception that can escape a trait-typed call must be handled, or declared in
the caller’s
!set, exactly like a direct call. Otherwise it is E0005.
Unified class header: class Foo : Base, Trait
The : form lists the base class and the traits together, separated by commas,
after a single :. Sema classifies each entry from its declaration. A class has
at most one base class; a second one is E0033.
class Shape {
pub name : string;
constructor(name : string) {
self.name = name;
}
pub fn describe(self) : string {
return self.name;
}
}
trait Renderable {
fn render(self) : string;
}
trait Serialisable {
fn toJson(self) : string;
}
// Shape is the base class; Renderable and Serialisable are traits.
class Sprite : Shape, Renderable, Serialisable {
x : i32;
y : i32;
constructor(name : string, x : i32, y : i32) {
super(name);
self.x = x;
self.y = y;
}
pub fn render(self) : string {
return self.name + " at " + self.x + "," + self.y;
}
pub fn toJson(self) : string {
return "{\"name\":\"" + self.name + "\"}";
}
} Only the first entry may be a base class. Every entry after it is a trait.
Default method bodies
A trait method may carry a default body: an implementation a class inherits when it does not supply its own.
trait Printable {
fn show(self) : string;
fn print(self) : void { // default body
println(self.show());
}
}
class Label : Printable {
text : string;
constructor(text : string) {
self.text = text;
}
pub fn show(self) : string {
return self.text;
}
// print() is inherited from the trait default
}
fn main() : i32 {
let lbl : Label = new Label("hello");
lbl.print(); // prints "hello"
return 0;
} A class that omits a defaulted method still satisfies the contract: the compiler grafts the trait body onto the class. A class may override the default by providing its own method of the same name and signature.
The inherited default is callable on a concrete binding (lbl.print() above) and through a trait-typed receiver (fn run(p : Printable) { p.print(); }).
It resolves regardless of declaration order: a defaulted method may be called
before its class is declared in the file. The graft also crosses a crate
boundary. A default body on a trait imported from another crate, including the
stdlib’s Rankable, travels in the package metadata and is grafted onto the
implementer the same way.
A default body on a trait from a dependency crate of your workspace is
grafted onto your class, struct or enum when it names only literals, self, its
own parameters and the methods and fields reached through them. A default that
calls a free function of the trait’s crate, writes a type by name, or declares a
local is refused with E0026 at the implementer; write the method there, or
reduce the default. A class that implements a trait but ends up with no body
for a method is always a compile error, never a failure when the call runs.
impl blocks: a type satisfies a trait without declaring it
An impl Type : Trait { method => body } block, written inside the trait,
lets a concrete type satisfy it without a : Trait clause on the type.
This is how a primitive such as i32 can satisfy a user trait’s bound, and
how a struct or enum can carry a trait without changing its declaration.
The trait itself is still declared; the block is the trait author’s side of
the bargain.
Each arm names the contract method it answers, so a trait may declare any number of methods:
trait Describable {
fn describe(self) : string;
fn size(self) : i32;
impl i32 : Describable {
describe => "an integer",
size => 4,
}
impl f64 : Describable {
describe => "a float",
size => 8,
}
}
fn take(x : Describable) : string {
return x.describe();
}
fn main() : i32 {
let n : i32 = 42;
println(n.describe()); // "an integer"
println(take(n)); // the same body, reached through a trait slot
return 0;
} An arm body is one of three forms, plus a rejection marker:
| Form | Meaning |
|---|---|
size => 4 | an inline expression; self is the receiver value |
size => { return 4; } | a block |
size => sizeOf(self) | an ordinary call |
size => unsupported "msg" | the type satisfies a bound but cannot be called: a direct or bound call is E0015 |
A method with a default may be omitted; the default runs for that type. A
class is not a target: it carries its own : Trait clause (E0784). A
generic trait is refused for now (E0780): the contract names its type
parameters and a bound does not bind its arguments yet.
A type in a block can also flow where a trait-typed value is expected: as an
argument (take(42)), as a variable (let x : Describable = 42;), or as a
return value. At each such boundary the compiler boxes the value in a small
synthesised wrapper that carries the type tag, so trait dispatch works
unchanged.
The box is a plain field copy, so it is offered only for a type whose copy
owns nothing: a numeric, bool or char primitive, or a struct or enum whose fields and payloads are all such primitives. Everything else in the
block keeps its statically dispatched method and still satisfies a bound, but
it cannot flow into a trait-typed slot. take(s) with s : string is E0001, because a box holding a string would own a buffer that the
box’s copy does not release.
Note An escaping boxed value held through a trait-typed binding (returned, or stored in a trait-typed field) is kept alive rather than freed once. The cost is a small, bounded leak. There is no dangling read and no double free.
dyn Trait: explicit trait objects
dyn Trait is another spelling for a trait-typed receiver. It resolves to the
same trait type and uses the same run-time dispatch, so there is no difference
at run time.
fn process(r : dyn Reader) : i32 { // same as fn process(r : Reader)
return r.read();
} Use dyn Trait when you want the dynamic dispatch visible in a signature.
Value types implementing traits: struct and enum
A struct and an enum are value types. They have no type header and are not
heap-allocated on their own. Each may declare inherent methods, and each may
implement a trait with the same : Trait clause a class uses. Conformance is
checked the same way: E0026 for a missing contract method, E0029 for a
signature mismatch.
When the value type is not yours to edit, the trait’s author can equip it from
the trait with an impl block instead; the two routes are exclusive for one trait and one type (E0783).
trait Area {
fn area(self) : i32;
}
struct Rect : Area {
w : i32;
h : i32;
pub fn area(self) : i32 { // inherent method, self receiver
return self.w * self.h;
}
}
enum Shape : Area {
Circle(i32),
Square(i32),
pub fn area(self) : i32 {
return match self { // the enum receiver is the value itself
Shape::Circle(r) => r * r,
Shape::Square(s) => s * s,
};
}
}
fn total(a : Area) : i32 { // trait-typed slot: dynamic dispatch
return a.area();
} When a value type flows into a trait-typed slot, the compiler wraps it in a
small tagged box whose leading __type_id names the concrete type. The same
run-time dispatch a class uses then works unchanged. A struct receiver crosses
by pointer and an enum by value, matching how its inherent methods take self.
Trait defaults are grafted onto value types too. A struct or enum that
omits a defaulted trait method inherits the trait’s body, lowered against the
implementer. In that body, a struct’s receiver is its pointer and an enum’s is
its value, so match self in the default reads the variant tag.
Note Only value types whose fields or payloads are trivially copyable are boxed. A value that owns a resource, such as a heap string or an owning pointer, would risk a double free on the box copy, so it is refused at the trait boundary rather than boxed.
when T : Bound: conditional method groups
A when block makes a group of methods exist only on instantiations where the
named bound holds. A generic class can then expose richer behaviour for capable
type arguments, without making the bound mandatory for every use.
class Holder<T> {
item : T;
count : i32;
constructor(own it : T, c : i32) { // `own` moves a class-typed T into the field
self.item = it;
self.count = c;
}
when T : Printable {
pub fn describeCount(self) : i32 {
return self.count; // only present when T : Printable
}
}
} Holder<Label> exposes describeCount, because Label : Printable. Holder<i32> does not. Calling the method on an instantiation that does not
satisfy the bound is E0015 (method not found). The gated methods are added to
each satisfying instantiation during monomorphisation.
Constructors and super
class Base {
id : i32;
constructor(id : i32) {
self.id = id;
}
}
class Derived : Base {
extra : string;
constructor(id : i32, extra : string) {
super(id); // MUST be first
self.extra = extra;
}
} Rules:
- Call
super(...)as the first statement of a derived constructor. - Suppose the nearest ancestor that declares constructors has no zero-argument
entry. Then a derived constructor that never reaches a
super(...)is E0777. The object is allocated zeroed, so the inherited fields would read as0ornull. - A class with no base in its
:list needs nosuper()call. A base with no constructor at all needs none either. - A derived constructor that does not start with
super(...)runs the nearest ancestor’s zero-argument constructor first, as ifsuper()were written. Writesuper(...)yourself to pick another constructor or its arguments.
Field access and self
class Counter {
value : i32;
constructor() {
self.value = 0;
}
pub fn bump(mut self) : void {
self.value = self.value + 1;
}
pub fn reset(mut self, value : i32) : void {
self.value = value; // disambiguates from the parameter
}
} self is required for field access inside methods. There is no implicit field
shadowing: value alone refers to the parameter, and self.value to the field.
Runtime type tests: is, !is and as downcast
Each class instance carries a hidden type tag, stamped at allocation, so a run-time type test is a real comparison.
x is Tandx !is Ttest a value’s run-time type againstTand its subclasses.- A successful
isnarrows the binding. Inside the proven scope, a base-typed local or parameter is seen as the subclass, so its members resolve. The narrowing covers only the then-branch (or the guarded body). It is dropped if the binding is reassigned.if (x !is T)narrows the else-branch the same way.
fn measure(s : Shape) : i32 {
if (s is Square) {
return s.area(); // s seen as Square here, so Square.area()
}
return 0;
} - An upcast (subclass to ancestor) is always free and needs no check.
- A downcast
x as Subis allowed only where anishas already proven the type. Theisis the run-time check, so theasis a zero-cost reinterpretation. An unproven downcast is rejected. There is no unchecked downcast.
class Animal {
pub legs : i32;
constructor(legs : i32) {
self.legs = legs;
}
}
class Dog : Animal {
pub barks : i32;
constructor(barks : i32) {
super(4);
self.barks = barks;
}
}
fn main() : i32 {
let b : Animal = new Dog(5);
if (b is Dog) {
let d : Dog = b as Dog; // proven by the `is`, so a reinterpretation
return d.barks;
}
return 0;
} Cross-trait tests: capability narrowing
is and as also work between traits. A value held as one trait, or as a
base class, can be asked at run time whether it has a different trait
capability. The test asks whether the value’s concrete type is among the types
that implement the queried trait. A proven is narrows the binding to that
trait view, so its methods resolve and dispatch through the type tag.
A dyn Trait[] is a heterogeneous array: each element may be a different
concrete implementer, stored behind the trait view. A dyn Trait[] literal (or
a scalar T[] literal) is a dynamic array. It lives on the heap with a
length header, so it can be passed to a T[] parameter and returned from a
call, with bounds checks and a release driven by that header.
trait Mob {
fn hit(mut self) : void;
}
trait Flies {
fn flee(mut self) : void;
}
class Goblin : Mob {
hp : i32;
constructor() { self.hp = 10; }
pub fn hit(mut self) : void { self.hp = self.hp - 1; }
}
class Bat : Mob, Flies {
hp : i32;
constructor() { self.hp = 3; }
pub fn hit(mut self) : void { self.hp = self.hp - 1; }
pub fn flee(mut self) : void { self.hp = 0; }
}
fn shockwave(mut mobs : dyn Mob[], n : i32) : void {
for (i of 0..n) {
let m : dyn Mob = mobs[i];
m.hit(); // the Mob contract: every element has it
if (m is Flies) { // does this element's concrete type fly?
(m as Flies).flee(); // proven: dyn Flies view, Flies dispatch
}
}
}
fn main() : i32 {
let g : Goblin = new Goblin(); // Goblin : Mob
let b : Bat = new Bat(); // Bat : Mob, Flies
let mobs : dyn Mob[] = [g, b]; // heterogeneous: mixed concrete types
shockwave(mobs, 2);
return 0;
} As with the class downcast, m as Flies is accepted only where a covering is Flies has proven it. An unproven capability downcast is E0001. A
statically known capability (a class to a trait it implements, or a sub-trait to
its super-trait) is always a free reinterpretation and needs no is.
Note A heap
T[]literal is offered for scalar and trait-object element types. An array of owning objects (a class with a destructor, aShared<U>, an ownedstring) keeps the fixed-size inline form, and it cannot cross a call yet.
Generics
class Box<T> {
value : T;
constructor(value : T) {
self.value = value;
}
pub fn get(self) : T {
return self.value;
}
}
fn main() : i32 {
let intBox : Box<i32> = new Box<i32>(42);
let strBox : Box<string> = new Box<string>("hi");
return intBox.get();
} The compiler monomorphises: it compiles one independent copy of the class
for each distinct tuple of concrete type arguments. Box<i32>, Box<string>, Box<Point> and Box<Circle> are four separate instances, each with its own
methods and its own exact field types, so a Box<Point> and a Box<Circle> never mix.
Because every instance is compiled for what its elements really are, an ArrayList<u32> sorts [4000000000, 1] to [1, 4000000000], while an ArrayList<i32> over the same bits sorts them the other way.
Note A coarser “ABI dimension” (
i32,u32,i64,u64,f64,string) exists, but only to spell the symbol names of stdlib native shims. It never merges two instances. See Generics and traits.
Storing a class-typed T in a field takes an own constructor parameter, which
moves ownership into the field. The synthesised destructor of the instance then
frees that field exactly once, at scope exit.
Multiple type parameters
A user generic class may take several type parameters, each monomorphised independently:
class Pair<K, V> {
key : K;
value : V;
constructor(k : K, v : V) {
self.key = k;
self.value = v;
}
pub fn getKey(self) : K {
return self.key;
}
pub fn getValue(self) : V {
return self.value;
}
}
fn main() : i32 {
let p : Pair<i32, i64> = new Pair<i32, i64>(7, 100);
println(p.getKey().toString() + " " + p.getValue().toString());
return 0;
} Fields use a type parameter directly, as in key : K and value : V. The
stdlib ships ready-made containers, ArrayList<T> and HashMap<K, V>, so you
rarely need to write one. A class can also hold a concrete instantiation as a
field:
use std::collections::HashMap;
class Cache {
map : HashMap<string, i32>,
constructor() {
self.map = new HashMap<string, i32>();
}
pub fn put(self, own key : string, value : i32) : void {
self.map.put(key, value); // `own`: the map takes the key
}
pub fn get(self, key : string) : i32 | null {
return self.map.get(key); // null on a miss
}
} @derive(...): synthesised boilerplate
Decorate a class with @derive(Trait, …) to have the compiler synthesise the
standard implementation of each listed trait. The expansion is field by field,
so it stays correct as the class gains fields.
@derive(Eq, ToString)
class Vector2 {
x : f64;
y : f64;
constructor(x : f64, y : f64) {
self.x = x;
self.y = y;
}
}
fn main() : i32 {
let a : Vector2 = new Vector2(1.0, 2.0);
let b : Vector2 = new Vector2(1.0, 2.0);
if (a.equals(b)) {
println(a.toString());
}
return 0;
} | Derivable trait | Synthesises |
|---|---|
Eq | equals, field by field |
Ord | compareTo |
Hashable | hashCode |
ToString | toString |
Clone | clone |
clone is also what copy calls: a struct holding an object is duplicated
through the clone() its class declares, derived or written by hand. See Structs: copy and own.
A name collision with a hand-written method of the same name is rejected at parse time. See Generics and traits for the full derivable-trait table and the generic bounds.
Method overriding and static dispatch
A subclass method with the same name overrides the base method, but there is no virtual table. A call resolves on the receiver’s declared type at compile time. A base class may supply a default body that subclasses override:
class Block {
// default body
pub fn surface(self) : i32 {
return 0;
}
// inherited unchanged
pub fn rank(self) : i32 {
return 10;
}
}
class Dirt : Block {
depth : i32;
constructor(depth : i32) {
self.depth = depth;
}
// override
pub fn surface(self) : i32 {
return 1;
}
} dirt.surface() on a Dirt binding runs Dirt.surface. The same call through
a Block-typed binding runs Block.surface. To dispatch on the concrete type
behind a base-typed binding, narrow it with an is test
(if (b is Dirt) { b.surface(); }), or model the capability as a trait, whose receiver dispatches at run time.
Comparing classes and traits
| You want to | Use |
|---|---|
| Share fields and method bodies | a base class (class Child : Base) |
| Document a contract several classes satisfy | a trait, satisfied with : Trait in the class header |
| Runtime polymorphism (a different body per concrete type) | a trait-typed or dyn Trait parameter, or is-narrowing of a base binding |
A shared implementation a primitive or value type can opt into without a : Trait clause | a trait with an impl Type : Trait block |
| Layered specialisation (Shape, then Circle, then ColoredCircle) | an inheritance chain |
Synthesise equals, compareTo, hashCode, toString or clone | @derive(Eq, Ord, Hashable, ToString, Clone) |
Lifetime patterns
Most classes are heap-allocated (new Foo(...)). Reach for Shared<T> only
when ownership really must be shared:
// Stack or heap, the compiler picks: single owner, escapes via return.
fn makePoint(x : f64, y : f64) : Point {
return new Point(x, y);
}
// Shared: one logical instance, several holders.
class HitCounter {
pub hits : i32,
constructor() { self.hits = 0; }
}
fn recordHit(counter : Shared<HitCounter>) : void {
counter.hits = counter.hits + 1; // fields are reached through the handle
}
fn buildCounter() : Shared<HitCounter> {
let counter : Shared<HitCounter> = share new HitCounter();
recordHit(counter);
return counter;
} See Memory model for how the tier is chosen.
Cleanup: drop(), defer and close()
A class may declare a destructor named drop(). The compiler runs it
deterministically when the instance’s lifetime ends: at scope exit for an owned
stack or heap instance, and at refcount zero for a Shared<T>. Memory itself
never needs a hand-written hook. A class that owns heap fields, owned objects,
or Shared<T> and Weak<T> handles gets a compiler-synthesised destructor that
frees them. Write an explicit drop() only to release a non-memory resource
the compiler cannot see.
For a resource you want released at a precise point, or on a borrowed handle
that the callee does not own, use the close() method convention. Every stdlib
I/O class follows it, and it pairs with defer:
class FileHandle {
pub fd : i32;
constructor(fd : i32) {
self.fd = fd;
}
pub fn close(mut self) : void {
// release self.fd here
self.fd = 0;
}
}
fn runWith(h : FileHandle) : i32 {
defer h.close();
return h.fd; // computed before the deferred close runs
} defer statements run when the block that registered them exits. At the top
level of a function body, that is function exit. They run in LIFO order, on
every exit path: a normal return, an early return, or a propagating exception.
Memory needs no hand-written hook: the compiler inserts the drop when a heap
instance leaves scope, and a Shared<T> is freed when its refcount reaches
zero.
Common pitfalls
Forgetting super(…) in a derived constructor
class Derived : Base {
extra : string;
constructor(extra : string) {
self.extra = extra; // E0777: the base constructor never runs
}
} The base constructor never runs, so id would read as 0. The compiler refuses
the program: when no super(…) can be written without arguments, one must be
called on every path that completes the constructor. Call super(id) explicitly.
Reading a field before the constructor sets it
class A {
x : i32;
constructor() {
// bug: the initialiser reads x before anything has set it
self.x = self.x + 1;
}
} Fields are zero-initialised before the constructor body runs, so x reads as 0 here. The clean version takes the value as a parameter:
class A {
x : i32;
constructor(start : i32) {
self.x = start + 1;
}
} Comparing class instances with ==
class Point {
x : f64;
y : f64;
constructor(x : f64, y : f64) {
self.x = x;
self.y = y;
}
}
fn main() : i32 {
let a : Point = new Point(1.0, 2.0);
let b : Point = new Point(1.0, 2.0);
if (a == b) { // identity check, not value
return 1;
}
return 0;
} == on class types compares pointer identity. For value equality, add an equals(other : Point) : bool method, or derive Eq.
Limits / Uncabled
| Feature | State | Workaround |
|---|---|---|
| Multiple base classes | Not supported: a class has one base | Put shared capabilities in traits |
| Virtual dispatch through a base-typed class variable | Not provided: class calls resolve on the declared type | Narrow with is, or model the capability as a trait |
| A generic trait carrying an impl block | Refused (E0780): a generic bound does not bind its arguments yet | Apply the trait at the type site, or drop the type parameter |
| A class as an impl-block target | Refused (E0784): a class carries its own : clause | Declare : Trait on the class |
for (x of collection) over a user collection without a protocol | Rejected with E0517 | Declare hasNext() / next() or nextSlot() / elementAt() (Iterating your own types), or write an index loop |
Heap T[] literal of owning objects | Not offered: an array of classes with destructors, Shared<U>, or owned strings stays inline | Use ArrayList<Shared<T>> for a growable collection of owned objects |
| A boxed primitive escaping through a trait-typed binding | Kept alive once, not freed (a bounded leak) | Return the primitive by value where the trait boundary is not needed |
| Unchecked downcast | Not provided: as downcast needs a covering is | Test with is first |
See also
- Language tour: classes
- Generics and traits: bounds
<T : A + B>,match type, the full@derivetable,when T : Bound std/collectionsreference: generic class examples- Error handling: exception subclasses
- Memory model: heap or shared storage
Shared<T>reference counting: when to opt in- Concept index: every class-related concept on one page