Skip to main content

Auto Traits

Auto traits are compiler generated implementations for commonly needed behaviour such as converting to string, testing for equality, and converting to and from json

These are the auto traits that exist:

  • Eq (used by the == and != operators)
  • Ord (used by the >, >=, <, <= operators and the ord method)
  • ToString (used by the to_string method)
  • ToJson (used by the to_json method)
  • FromJson (used by the parse_json function)
  • Hash (used by the hash method)
  • Clone (used by the clone method)
  • Copy (implemented by every type, used by assignment)

The compiler provides implementations of these auto traits for every primitive type

You can instruct the compiler to generate a definition for your structs by using the auto attribute

The auto attribute

src/auto.duck

[auto(ToString, Eq)]
struct Person {
name: String,
age: Int,
}

fn main() {
const p = Person {
name: "John Smith",
age: 32,
};

std::io::println(p.to_string()); // <- Without the auto attribute on Person, this call will fail

const persons = [Person { name: "John the 1st", age: 33 }, Person { name: "John the 2nd", age: 34 }];
std::io::println(persons.to_string()); // <- An array of persons implements ToString, because Person implements ToString

if (p == Person { name: "John Smith 2", age: 40}) { // <- the == operator now uses the Eq implementation of Person
std::io::println("equal");
} else {
std::io::println("not equal");
}
}