liveBook · Manning

Orphan rule

As explained in Write Powerful Rust Macros

An orphan rule restricts trait implementations so that at least the trait or the implemented type is local to the defining crate.

Rust requires an implementation to involve a local trait, a local type, or both. This prevents competing implementations for the same trait and type. section 2.2.3

Wrapping a nonlocal type

You cannot freely implement Clone for the nonlocal type String. Wrap String in a local newtype such as MyString, then implement Clone for MyString. Newtypes provide the workaround without runtime overhead, while macros can reduce the resulting boilerplate. section 2.2.3

Listing 2.7 The FirstName newtype
struct FirstName {
    value: String,
}

impl FirstName {
    pub fn new(name: &str) -> Result<FirstName, String> {
        if name.len() < 2 {
            Err("Name should be at least two characters".to_string())
        } else {
            Ok(FirstName {
                value: name.to_string(),
            })
        }
    }

    pub fn get_value(&self) -> &String {
        &self.value
    }
}

// code for the other three newtypes

fn calculate_raise(first_name: FirstName, #1
                   _last_name: LastName,
                   _age: Age,
                   current_pay: Pay) -> Pay {
    // ...
}

Inspect a Rust newtype that wraps String and exposes a controlled value accessor. section 2.2.3

How Write Powerful Rust Macros covers it

How deep it goes
Explains the locality requirement, conflicting-implementation rationale, and newtype workaround, but does not detail compiler coherence internals.
Examples
Uses a hypothetical Clone implementation for String and a MyString newtype as the concrete workaround.
What it assumes
Assumes Rust trait and type familiarity while explaining the locality constraint and newtype technique directly.
What you can do after
Apply it via a local newtype to implement traits for otherwise nonlocal types.
How it connects
Connects orphan rules with traits, newtypes, wrapper types, Clone, String, and declarative macros.

Also explained in

Compare how 2 books explain orphan rule →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.