简体   繁体   中英

How can a rust `new` method know which generic type of structure to return?

I'm learning Rust and one thing didn't seem right

let vector: VecDeque<u32> = VecDeque::new();

How can the new method know which type of VecDeque to return? Could be VecDeque<T> for any T . I come from C++ where, if there were a static new method it'd have to be templated and I'd have to call like this: CppObject<int> cppObject = CppObject<int>() for example.

Rust does a lot of type inference. In this case, it knows to call VecDeque::<u32>::new() because you explicitly specified that you want to assign it to a variable of type VecDeque<u32> and the only way you can get there is if you call the associated method new() on exactly the type VecDeque<u32> .

Note that if you did not annotate the type of vector , it would fail to compile:

use std::collections::VecDeque;

fn main() {
    let vector = VecDeque::new();
}
error[E0282]: type annotations needed for `std::collections::VecDeque<T>`
 --> src/main.rs:4:18
  |
4 |     let vector = VecDeque::new();
  |         ------   ^^^^^^^^^^^^^ cannot infer type for type parameter `T`
  |         |
  |         consider giving `vector` the explicit type `std::collections::VecDeque<T>`, where the type parameter `T` is specified

But the compiler will also successfully infer the type if there are operations afterwards that make clear that VecDeque elements are of type u32 :

use std::collections::VecDeque;

fn main() {
    let mut vector = VecDeque::new(); // type not yet known
    vector.push_back(123);            // append untyped integer, type not yet known

    let expected: u32 = 123;
    assert_eq!(vector[0], expected); // A-ha! vector[0] returns T
                                     // and T is compared with u32,
                                     // so it must follow that T is u32
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM