Skip to content

Suggest replacing const with let on "can't use generic parameters from outer item" (outer fn specifically) (if appropriate)  #68373

@sm-Fifteen

Description

@sm-Fifteen

I tried this code, assuming the result of size_of::<T>() would be considered a constant value since it would be known at function monomorphization:

const fn size_plus_one<T:Sized>() -> usize {
    const size: usize = ::core::mem::size_of::<T>();

    size + 1
}

This resulted in the following compilation error:

error[E0401]: can't use generic parameters from outer function
 --> src/lib.rs:2:48
  |
1 | const fn size_plus_one<T:Sized>() -> usize {
  |                        - type parameter from outer function
2 |     const size: usize = ::core::mem::size_of::<T>();
  |                                                ^ use of generic parameter from outer function

As it turns out, the error message here is incorrect, and the issue can be solved by using let instead, something the error message was rather unhelpful with.

const fn size_plus_one<T:Sized>() -> usize {
    let size: usize = ::core::mem::size_of::<T>();

    size + 1
}

PLAYGROUND LINK

Meta

rustc 1.40.0 (73528e339 2019-12-16)
binary: rustc
commit-hash: 73528e339aae0f17a15ffa49a8ac608f50c6cf14
commit-date: 2019-12-16
host: x86_64-unknown-linux-gnu
release: 1.40.0
LLVM version: 9.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-resolveArea: Name/path resolution done by `rustc_resolve` specificallyD-lack-of-suggestionDiagnostics: Adding a (structured) suggestion would increase the quality of the diagnostic.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions