Skip to content

Type inference tries to put the unsizing coercion in the wrong place #149881

@RalfJung

Description

@RalfJung

I tried this code:

fn id<T>(x: Box<T>) -> Box<T> { x }

fn main() {
    <[_]>::into_vec(id(Box::new([0, 1, 2])));
}

This fails to compile:

error[E0277]: the size for values of type `[{integer}]` cannot be known at compilation time
 --> src/main.rs:4:24
  |
4 |     <[_]>::into_vec(id(Box::new([0, 1, 2])));
  |                     -- ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |                     |
  |                     required by a bound introduced by this call
  |
  = help: the trait `Sized` is not implemented for `[{integer}]`

However, there's not really a good reason for that... there is a way to instantiate the generic arguments to make this work, as follows:

fn id<T>(x: Box<T>) -> Box<T> { x }

fn main() {
    <[_]>::into_vec(id::<[i32; 3]>(Box::new([0, 1, 2])));
}

This compiles fine.

This came up in #148190 where unfortunately, adding the extra type annotation or making things ?Sized are both not feasible. I also don't really understand why this is a problem, given that Box::new also has T: Sized side-condition and that works just fine. But then somehow wrapping it in another function with the same side-condition breaks inference.
Cc @BoxyUwU

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-DSTsArea: Dynamically-sized types (DSTs)A-coercionsArea: implicit and explicit `expr as Type` coercionsA-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-typesRelevant to the types 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