MARY.WIN

RUSTY — LARAVEL TO RUST — 08

Traits versus
PHP interfaces

Substitute an executor without changing its caller.
Tutorial 8 of 16 in From Laravel to Rust. Before you start: Result and borrowing.

Can the same caller use an executor that succeeds and one that refuses work? In examples/src/bin/ep08.rs, the Executor trait declares execute(). FakeExecutor and BusyExecutor implement that method with different results. The generic run() function accepts either implementation.

FakeExecutor::execute() returns simulated: tests for the title tests. BusyExecutor::execute() returns RunError::Busy. Neither implementation launches a process. Their purpose is to make the caller’s substitution path observable.

The example uses synchronous calls. First inspect the trait signature, then follow each run() call to the supplied implementation. Compare the success and failure values before considering a runtime-selected trait object.

This lesson covers Rust traits as capability contracts: declaring one, implementing it for two types, and writing a caller that accepts either. It also covers the choice between generics and dyn trait objects at the level of “when is the implementation selected”. It leaves out async traits and associated types. It assumes Tutorials 3 and 7. A warning about the word first: a PHP trait supplies reusable implementation to classes. The closer PHP starting point for a Rust trait is an interface.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep08.rs)

#[derive(Debug, PartialEq)]
enum RunError { Busy }

trait Executor {
    fn execute(&self, title: &str) -> Result<String, RunError>;
}

struct FakeExecutor;
impl Executor for FakeExecutor {
    fn execute(&self, title: &str) -> Result<String, RunError> {
        Ok(format!("simulated: {title}"))
    }
}

struct BusyExecutor;
impl Executor for BusyExecutor {
    fn execute(&self, _: &str) -> Result<String, RunError> {
        Err(RunError::Busy)
    }
}

fn run<E: Executor>(executor: &E, title: &str)
    -> Result<String, RunError>
{
    executor.execute(title)
}

fn main() {
    assert_eq!(run(&FakeExecutor, "tests"), Ok("simulated: tests".into()));
    assert_eq!(run(&BusyExecutor, "tests"), Err(RunError::Busy));
    println!("both implementations use the same caller");
}

Run it from the examples/ directory.

Expected output:

TERMINAL
cargo run --quiet --bin ep08
both implementations use the same caller

The caller that did not choose

run declined to choose an executor. Its body was one line, executor.execute(title), and its signature asked only that the type implement Executor. In main it was handed FakeExecutor and the title "tests", and it returned the string simulated: tests inside Ok. On the next line it was handed BusyExecutor and the same title, and it returned Err(RunError::Busy). Nothing in run had changed between the two lines. The terminal printed both implementations use the same caller.

Sometimes one operation has to work with an executor that succeeds and with one that refuses, and writing the operation twice is not the plan. Thankfully, the operation can depend on the capability and leave the choice to its caller. Take another look at Example 1.

There are three pieces. The trait Executor declares one method: execute(&self, title: &str) borrows the executor and the title, and its Result<String, RunError> return type provides owned output or a structured failure. Two unit structs implement it, with different results. And run<E: Executor> accepts a reference to any type that implements the trait and forwards the title directly to executor.execute(title).

Generic or dyn?

The bound E: Executor requires the supplied type to implement Executor. In run(&FakeExecutor, "tests"), E is FakeExecutor; in run(&BusyExecutor, "tests"), E is BusyExecutor. The compiler can specialize the generic code for those concrete types.

You can also select at runtime. A compatible trait can be used through a trait object, such as &dyn Executor or an owned Box<dyn Executor>. That changes dispatch and ownership choices.¹ If you're unsure, I'd ask three questions: when is the implementation selected, must different implementations share one collection, and who owns the selected collaborator.

The PHP comparison

In PHP we might define an Executor interface and pass an implementing object into a constructor. Rust traits declare behavior and can also carry default method implementations, and that still does not make them PHP's code-reuse mechanism. The bridge is the caller's expectation: “I need this capability.”

There are also coherence rules. You cannot freely implement any foreign trait for any foreign type; a local wrapper type can sometimes provide the boundary you own. Deciding where behavior belongs includes deciding which type and contract your package controls.

What the fake proves

The first assertion checks that run returns the string from FakeExecutor, the second checks that run preserves the error from BusyExecutor, and the terminal prints both implementations use the same caller after both pass, which is, however green the run and however closely simulated: tests resembles what a real executor might report, evidence about the caller and its substitution path, because no assertion in this file exercises an operating-system process.

Keep the claims separate. Unit tests check the application's handling of success and Busy. Adapter tests check command construction and failure translation. Integration tests exercise the real external boundary.

Do you need a trait at all?

Suppose the operation trims a title. A free function is likely enough; a TitleNormalizer trait with one permanent implementation adds a concept and no substitution point. For the executor the variation is real, a fake and a boundary implementation with different effects, so the trait has work to do.

Keep the contract narrow even then. An interface called ApplicationServices that includes storage, logging, time, process execution, and UI notifications would hide which capability the caller needs.

So run works with both implementations. Now find one interface in your Laravel application with exactly one implementation. What change was it written to allow? Has that change happened? If it never does, what is the interface telling the next reader?

Testing

In Example 1, change run to accept &dyn Executor. Predict whether the existing success and busy assertions will still pass, and write the prediction down before you run the changed example.

Both implementations satisfy this trait object, so the two results remain the same. Dispatch now uses the trait object, while run still borrows its executor.

Next, add a third executor with a distinct output and verify it through run. That is the substitution test.

Then, as a negative control, construct FakeExecutor inside run instead of using the parameter. The busy assertion now detects the bypass. Restore the call to the supplied executor.

Last, explain the path from each run call to Executor::execute.

TL;DR

A Rust trait describes behavior a caller can depend on; the PHP comparison is an interface, not a PHP trait. The bound E: Executor lets the compiler specialize run for each concrete type, and trait objects allow selection at runtime. The supplied executor determines the result while run keeps the same body. A fake is evidence about the caller and about nothing past it. A trait is worth declaring where the variation is real. Next: moving that choice into application construction, so the caller's collaborator is selected once.

¹ A trait object is not a universal replacement for generics, and not every trait is dyn-compatible.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Rust Book, Defining Shared Behavior with Traits and Using Trait Objects; Rust Reference, dyn compatibility and coherence; PHP Manual, interfaces and traits.

NOT CHECKED — 5
  • That both assertions still pass after run takes &dyn Executor. This exercise is not among the checks run for this edition.
  • That the busy assertion fails when run builds its own FakeExecutor.
  • That the compiler specializes run for each concrete type. The page states this but does not show it.
  • The comparison with PHP interfaces and PHP traits. No PHP was run for this page.
  • The reference links were not opened for this page.