Patterns for per-function return types

⚓ Rust    📅 2026-06-28    👤 surdeus    👁️ 2      

surdeus

What means exist to tie a type to a function?

Sometimes I have per--function return values:

enum Outcome {
  Process(Frame),
  Skip,
  Terminate
}
fn foo() -> Outcome {
  // ...
}

And sometimes the name of these return type collide with other types. What means exist to "tie" the type together with the function (with the specific goal of avoiding name collisions and clarifying that the type belongs to a specific function)? Renaming the type and using modules are the obvious answers, but are there other ways?

This doesn't work because enums can't be defined in impl blocks:

struct Foo;

impl Foo {
  pub enum Outcome {
    Process(Frame),
    Skip,
    Terminate
  }
  pub fn do_foo() -> Outcome {
  }
}

It would be nice to return a local enum, which would end up as a kind of anonymous enum to the caller:

pub fn foo() -> Outcome {
  enum Outcome {
    Process(Frame),
    Skip,
    Terminate
  }
  // ...
}

fn bar() {
  match foo() {
    _::Process(frm) => {
    }
    _::Skip => {
    }
    _::Terminate => {
    }
  }
}

Made-up Rust features/syntax aside, are there ways to accomplish this (beyond the obvious ones mentioned already)?

XY: Just curious. Modules work fine for this, but I'm curious if there are other patterns people use for this sort of thing.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed