Skip to content
This repository has been archived by the owner on May 23, 2020. It is now read-only.

Update trait static methods using Self to use UFCS once available in language #3

Closed
oko opened this issue Dec 3, 2014 · 3 comments
Closed
Assignees

Comments

@oko
Copy link
Owner

oko commented Dec 3, 2014

Traits using Self to in static method parameters are called through the trait rather than the implementer. Type hinting currently requires addition of a throwaway typed parameter:

impl RData for A {
    ...
    fn from_rdata(rdata: &[u8], _ignored: Option<A>) -> Result<A, &'static str> {
        let rlen = rdata.len();
        ...
    }
}

Once UFCS is completed hopefully the call syntax will change.

Requires completion of rust-lang/rust#16293

@oko oko self-assigned this Dec 3, 2014
@ghost
Copy link

ghost commented Jan 1, 2015

It's possible get this to work without requiring a dummy method parameter:

trait Is<A> {}
impl<A> Is<A> for A {}

trait RData {
    fn from_rdata<X: Is<Self>>(_rdata: &[u8]) -> Result<Self, &'static str>
        // adding the bound on Self here is optional but allows the X
        // parameter to be omitted given an outer annotation; see the
        // `l` binding below in `main`
        where Self: Is<X>;
}

impl RData for u16
{
    fn from_rdata<X>(_rdata: &[u8]) -> Result<Self, &'static str> {
        Ok(0u16)
    }
}

impl RData for bool
{
    fn from_rdata<X>(_rdata: &[u8]) -> Result<Self, &'static str> {
        Ok(true)
    }
}

fn main() {
    let x: &[u8] = &[];
    let l: Result<u16, _> = RData::from_rdata(x);
    let r = RData::from_rdata::<bool>(x);
    println!("{} {}", l, r);
}

@oko
Copy link
Owner Author

oko commented Jan 1, 2015

That's an improvement. May go with this if there's still no movement on UFCS in the near future.

@ghost
Copy link

ghost commented Jan 1, 2015

Yeah… also if equality constraints for where clauses land sometime soon it should allow this same trick without having to define the Is trait.

@oko oko closed this as completed May 21, 2015
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant