Skip to content

Suggest reborrowing unsized value when borrowed trait object wanted #93596

@ijackson

Description

@ijackson

Given the following code:

use std::ffi::{OsStr, OsString}; use std::path::Path; fn check(p: &dyn AsRef<Path>) { let m = std::fs::metadata(&p); println!("{:?}", &m); } fn main() { let s: OsString = ".".into(); let s: &OsStr = &s; check(s); }

The current output is:

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time --> src/main.rs:12:11 | 12 | check(s); | ----- ^ doesn't have a size known at compile-time | | | required by a bound introduced by this call | = help: within `OsStr`, the trait `Sized` is not implemented for `[u8]` = note: required because it appears within the type `OsStr` = note: required for the cast to the object type `dyn AsRef<Path>` 

Ideally the output would suggest borrowing, since this:

 check(&s); 

compiles and works just fine.

The problem is that you can't make an object which is a wide pointer directly into a trait object refernce, because it would have to be a triple-sized pointer. But often, you can just reborrow instead.

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`A-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.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