Skip to content

rustc decides variable is of unsized type even when it is clear later it's not #118572

Open
@ChayimFriedman2

Description

@ChayimFriedman2

I tried this code:

fn any<T>() -> T { loop {} }

fn foo() {
    let v = any();
    let r: &[i32] = &v;
    let _: [i32; 1] = v;
}

Playground.

I expected to see this happen: compiles successfully, with v deduced to be [i32; 1]

Instead, this happened:

error: mismatched types
 --> src/lib.rs:6:23
  |
5 |     let r: &[i32] = &v;
  |                      - here the type of `v` is inferred to be `[i32]`
6 |     let _: [i32; 1] = v;
  |            --------   ^ expected `[i32; 1]`, found `[i32]`
  |            |
  |            expected due to this

error: the size for values of type `[i32]` cannot be known at compilation time
 --> src/lib.rs:4:9
  |
4 |     let v = any();
  |         ^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `[i32]`
  = note: all local variables must have a statically known size
  = help: unsized locals are gated as an unstable feature

error: the size for values of type `[i32]` cannot be known at compilation time
 --> src/lib.rs:4:13
  |
4 |     let v = any();
  |             ^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `[i32]`
note: required by a bound in `any`
 --> src/lib.rs:1:8
  |
1 | fn any<T>() -> T { loop {} }
  |        ^ required by this bound in `any`
help: consider relaxing the implicit `Sized` restriction
  |
1 | fn any<T: ?Sized>() -> T { loop {} }
  |         ++++++++

rustc assumes v: [i32], and then fails both because it's an unsized type and because it can't match with let _: [i32; 1] = v;.

Strangely enough, it does compile with trait objects:

fn any<T>() -> T { loop {} }

fn foo() {
    let v = any();
    let r: &dyn std::fmt::Debug = &v;
    let _: [i32; 1] = v;
}

Playground.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions