Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use defaults from formal type parameters in type inference, as fallbacks. #13702

Closed
wants to merge 3 commits into from

Conversation

eddyb
Copy link
Member

@eddyb eddyb commented Apr 23, 2014

This enables more powerful uses of default type params, while maintaining backwards compatibility.

// A simple function example.
fn foo<T: Default = uint>() -> T {Default::default()}
println!("{}", foo());

// Making constructors generic over type params, falling back to a default.
// This allows making, e.g. containers parametric over an allocator without
// affecting existing code bases and without using different constructors.
#[deriving(Default)]
struct Heap;
struct Vec<T, A = Heap>(A);
impl<T, A: Default = Heap> Vec<T, A> {
    fn new() -> Vec<T, A> {
        Vec(Default::default())
    }
    fn push(&self, _: T) {}
}

// error: mismatched types: expected `main::Vec<<generic #1>>` but found `()`
let () = Vec::new(); // ^^ the error message omits A, it was inferred to Heap

let v = Vec::new();
v.push(5u); 
// error: mismatched types: expected `main::Vec<uint>` but found `()`
let () = v; // ^^ fully inferred type (again omitting A)

let v: Vec<_, char> = Vec::new();
v.push(5u);
// error: mismatched types: expected `main::Vec<uint, char>` but found `()`
let () = v; // ^^ overriding the defaults still works

Disclaimer: the current implementation is only a proof of concept, missing substitution (for <T, U = (T, T)>) and any form of lifetime environment (for <'a, T = &'a int>).

Also, I somehow managed to break overriding the defaults (the last example doesn't actually compile).
It seems odd given that fallbacls should only be used when force_tvar is set, and that shouldn't happen for let v: Vec<_, char> = Vec::new(); (otherwise our inference would be unusable).
cc @nikomatsakis

@thestinger
Copy link
Contributor

@eddyb: needs a rebase

@alexcrichton
Copy link
Member

Closing due to inactivity, but feel free to reopen with a rebase!

@pczarn
Copy link
Contributor

pczarn commented May 19, 2014

👍 this is precisely what I need. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants