Skip to content

Bogus T:Sized suggestion when using size_of::<T> as a const #69228

Closed
@bugaevc

Description

@bugaevc

Example:

use std::mem::size_of;

fn foo<T>() {
    let arr: [u8; size_of::<T>()];
}

playground

Results in the following error:

error[E0277]: the size for values of type `T` cannot be known at compilation time
   --> src/lib.rs:4:29
    |
3   | fn foo<T>() {
    |        - help: consider restricting this bound: `T: std::marker::Sized`
4   |     let arr: [u8; size_of::<T>()];
    |                             ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `T`
    = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>

of course, T is Sized by default unless you say T: ?Sized, so the error and the suggestion are clearly wrong. And if you do say T: Sized explicitly,

// Of course, an explicit Sized constraint doesn't help:
fn bar<T: Sized>() {
    let arr: [u8; size_of::<T>()];
}

you get

error[E0277]: the size for values of type `T` cannot be known at compilation time
   --> src/lib.rs:9:29
    |
8   | fn bar<T: Sized>() {
    |        -- help: consider further restricting this bound: `T: std::marker::Sized +`
9   |     let arr: [u8; size_of::<T>()];
    |                             ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `T`
    = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>

Note T: std::marker::Sized + being suggested, which is not even valid syntax apparently valid syntax, but not something you would write.

I expected to see this happen:

  • Either this compiles cleanly
  • Or the compiler emits a different error that makes sense

Meta

rustc --version --verbose:

rustc 1.41.0 (5e1a79984 2020-01-27)
binary: rustc
commit-hash: 5e1a799842ba6ed4a57e91f7ab9435947482f7d8
commit-date: 2020-01-27
host: x86_64-unknown-linux-gnu
release: 1.41.0
LLVM version: 9.0

(Seems to happen on nightly too.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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