I am trying to define a struct with a defaultable type parameter, the same way Vec works in Rust nightly with its allocator. However, as explained in other answers and the Rust forum, that's not how type inference works:
use std::marker::PhantomData;
struct Foo<X: Copy = i32> {
x: PhantomData<X>
}
impl<X: Copy> Foo<X> {
fn new() -> Foo<X> {
Foo {
x: PhantomData
}
}
}
fn main() {
// type annotations needed
let foo = Foo::new();
// works??
let mut bar = Vec::new();
bar.push(42); // to let Rust infer T.
}
My question is not why Foo::new() does not compile, but rather why Vec::new() still does. If I remove Foo::new(), the file compiles. As far as I understand it, the new definition of Vec to support allocators should've broken almost all code.
Ideally an answer would point me to the code in rustc that makes this exemption, if it is one.