Closed
Description
Consider code like this:
let values: [i32; 3] = [1, 2, 3];
do_stuff(&values);
This becomes annoying when you change the values on the right hand side, because you have to update the length on the left to match. In this case, it's often not necessary to be explicit about the type because it can be fully inferred. But there are cases where it's less convenient, such as with trait objects, where the inference can be too narrow without an annotation:
struct MyStruct;
trait MyTrait {}
impl MyTrait for MyStruct {}
fn main() {
let values = [&MyStruct, &MyStruct];
do_stuff(&values);
}
fn do_stuff(values: &[&MyTrait]) {}
This is an error unless you give a hint to the compiler that the array is of the trait object and not the impl. You can do it like this:
let values = [&MyStruct as &MyTrait, &MyStruct];
Which works, but the following would be much clearer:
let values: [&MyTrait; _] = [&MyStruct, &MyStruct];
Metadata
Metadata
Assignees
Labels
No labels