ideasman42
ideasman42

Reputation: 48128

How to ensure structs implement functions consistently, without callers having to explicitly 'use' the trait?

Given multiple similar structs, it may be useful to implement functions matching a signature.

The simple example below works nicely, but doesn't ensure all functions follow the same function signature.

impl FooStruct {
    pub fn calc_value(seed: i64) -> i64 { /* function body! */ }
}
impl BarStruct {
    pub fn calc_value(seed: i64) -> i64 { /* function body! */ }
}

Using a trait resolves this:

pub trait CanCalcValue {
    fn calc_value(seed: i64) -> i64;        
}

impl CanCalcValue for FooStruct {
    fn calc_value(seed: i64) -> i64 { /* function body! */ }
}
impl CanCalcValue for BarStruct {
    fn calc_value(seed: i64) -> i64 { /* function body! */ }
}

However, now I have to add use some_module::CanCalcValue; everywhere I wan't to call calc_value.

Is there some way to define a trait that can be used without having to ensure it's in the namespace?

Said differently, there are times when logically a trait makes sense in that multiple structs share a signature, but I avoid using it because it becomes annoying to have to use the trait all over the codebase.


Note: there is discussion on this topic in the RFC issue tracker, although no RFC currently.

Upvotes: 2

Views: 486

Answers (1)

Steve Klabnik
Steve Klabnik

Reputation: 15559

Is there some way to define a trait that can be used without having to ensure its in the name-space?

In short, no. To use a trait, you must import it. Without a trait, you can't ensure that the signatures are the same.

Upvotes: 8

Related Questions