Rfcs: trait support in type ascription

Created on 1 Sep 2016  路  6Comments  路  Source: rust-lang/rfcs

I want to be able to write expr: Trait to assert that the type of expr implements the trait Trait. Of course I don't think this exact syntax would work since we may at some point in the future want to allow Trait as a type (e.g., as DST-by-value function args). Perhaps expr: impl Trait would work? I realise that impl Trait is a type and that therefore this is ambiguous with regular type ascription, but it is a pretty magic type that can only be used in limited places, so maybe it works out.

The motivation here is debugging iterators, when I have some enormous iterator expression like

            a.def_names.get(name).map(|names| {
                names.into_iter().flat_map(|id| {
                    a.ref_spans.get(id).map_or(vec![], |v| v.clone()).into_iter()
                }).collect(): Vec<Span>
            }).ok_or(())

and somewhere in there I'm gettting &T rather T it would be nice to use type ascription to help find the error. However, because iterator types are hellish, it is pretty much impossible.

T-lang

Most helpful comment

I prefer the "barrier" interpretation. An impl trait whose abstraction boundary is always the current function doesn't seem very composable to me.

All 6 comments

x: impl Trait has interesting consequences. I see it as creating a "barrier", inferring a type before the ascription, and only exposing the API _after_ the ascription.
OTOH, one could argue that because you're within the same function, you should be able to see the type.

I prefer the "barrier" interpretation. An impl trait whose abstraction boundary is always the current function doesn't seem very composable to me.

Another idea is to introduce an attribute that triggers a lint or compile error after type inference:

a.def_names.get(name).map(|names| {
                #[isType(Vec<Span>)] names.into_iter().flat_map(|id| {
                    a.ref_spans.get(id).map_or(vec![], |v| v.clone()).into_iter()
                }).collect()
            }).ok_or(())

As someone who has used let x:() = ... as a type debugging mechanism, I like this idea.

Is this handled by impl Trait-in-let (https://github.com/rust-lang/rfcs/pull/2071)?

Closing in favor of #2522 and https://github.com/rust-lang/rfcs/pull/2071.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

3442853561 picture 3442853561  路  4Comments

rudolfschmidt picture rudolfschmidt  路  3Comments

3442853561 picture 3442853561  路  3Comments

marinintim picture marinintim  路  3Comments

burdges picture burdges  路  3Comments