Skip to content

Unable to infer trait's type parameter when using static method of trait #3902

Closed
@burg

Description

@burg

The following should compile correctly AFAIK, but the type parameter isn't being properly inferred.

Updated Testcase

use std::io::println;

mod base {
    pub trait HasNew<T> {
        #[cfg(buggy)]
        fn new() -> T;
        #[cfg(fixed)]
        fn new() -> Self; // (see niko's first comment in ticket)
    }

    #[deriving(Show)]
    pub struct Foo {
        dummy: (),
    }

    impl HasNew<Foo> for Foo {
        fn new() -> Foo {
            Foo { dummy: () }
        }
    }

    pub struct Bar {
        dummy: (),
    }

    impl HasNew<Bar> for Bar {
        fn new() -> Bar {
            Bar { dummy: () }
        }
    }
}

fn main() {
    // 1. You cannot say this:
    // let f: base::Foo = base::HasNew<base::Foo>::new();

    // 2. There are discussions to provide some way to say
    // something like this (see Issue 6894):
    // let f: base::Foo = base::HasNew<base::Foo, for base::Foo>::new();

    // 3. But for now, one must rely on the type inference system
    // to feed the appropriate type via the expression context in which
    // the invocation of `new` occurs:
    let f: base::Foo = base::HasNew::new();
    println(format!("{}", f).as_slice());
}

Original Outdated Testcase

mod base {
    trait HasNew<T> {
        static pure fn new() -> T;
    }

    pub struct Foo {
        dummy: (),
    }

    pub impl Foo : HasNew<Foo> {
        static pure fn new() -> Foo {
            Foo { dummy: () }
        }
    }

    pub struct Bar {
        dummy: (),
    }

    pub impl Bar : HasNew<Bar> {
        static pure fn new() -> Bar {
            Bar { dummy: () }
        }
    }
}

fn main() {
    let f: base::Foo = base::new::<base::Foo, base::Foo>();
    debug!("%?", f);
}

Error

% rustc --cfg buggy /tmp/base.rs
/tmp/base.rs:42:23: 42:40 error: cannot determine a type for this bounded type parameter: unconstrained type
/tmp/base.rs:42     let f: base::Foo = base::HasNew::new();
                                       ^~~~~~~~~~~~~~~~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait systemA-type-systemArea: Type systemE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.P-lowLow priority

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions