Skip to content

Type inference depends on ordering #42333

@mulkieran

Description

@mulkieran

This code ( https://is.gd/6jsqIt) gives the following compile error:

use std::path::PathBuf;

pub struct Thing {
    pub f1: PathBuf,
}

fn junk() -> Vec<Thing> {

    let mut things = Vec::new();
    for x in vec![1, 2, 3] {
        if x == 2 {
            for thing in things.drain(..) {
                thing.f1.clone();
            }
            return vec![]
        }
        things.push(Thing{f1: PathBuf::from(format!("/{}", x))});
    }   
    things  
}               
            
fn main() { 
    junk();
}
rustc 1.17.0 (56124baa9 2017-04-24)
error: the type of this value must be known in this context
  --> <anon>:13:17
   |
13 |                 thing.f1.clone();
   |                 ^^^^^^^^

error: aborting due to previous error

I believe that the type of the error should be known in the context, because the type of things is certainly known, and therefore the types of the elements yielded by things.drain(). Note that the error has to do with the publicly accessible f1 field of thing, which should be know to be PathBuf.

I can eliminate the error by adding a type annotation of Vec<Thing> to the declaration of things.

I can also eliminate the error by swapping the positions of the things.push line and the if x == 2 block.

These facts are true as of today for Stable, Beta, Nightly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions