Skip to content

Self-referential struct with Cow<[Self]> as the last field errors #89940

Closed as not planned
@mbartlett21

Description

@mbartlett21

I tried this code:

use std::borrow::Cow;

struct Element<'a> {
    arr: Cow<'a, [Element<'a>]>,
}

// So that `ToOwned` *should* be implemented for `[Element<'a>]`.
impl<'a> Clone for Element<'a> {
    fn clone(&self) -> Self {
        todo!()
    }
}

Compiling it, I got these errors:

error[E0277]: the trait bound `[Element<'a>]: ToOwned` is not satisfied
   --> src/lib.rs:4:10
    |
4   |     arr: Cow<'a, [Element<'a>]>,
    |          ^^^^^^^^^^^^^^^^^^^^^^ the trait `ToOwned` is not implemented for `[Element<'a>]`
    |
    = help: the following implementations were found:
              <[T] as ToOwned>

(this is presumably because there is a reference to the struct)

error[E0277]: the trait bound `[Element<'a>]: ToOwned` is not satisfied in `Element<'a>`
   --> src/lib.rs:7:10
    |
7   | impl<'a> Clone for Element<'a> {
    |          ^^^^^ within `Element<'a>`, the trait `ToOwned` is not implemented for `[Element<'a>]`
    |
    = help: the following implementations were found:
              <[T] as ToOwned>

note: required because it appears within the type `Element<'a>`
   --> src/lib.rs:3:8
    |
3   | struct Element<'a> {
    |        ^^^^^^^

A "fix"

Changing line 4 to use an Option works for no obvious reason, and will also add an extra cost to using the field:

  struct Element<'a> {
<     arr: Cow<'a, [Element<'a>]>,
>     arr: Option<Cow<'a, [Element<'a>]>>,
  }

Meta

rustc --version --verbose:

rustc 1.57.0-nightly (dfc5add91 2021-10-13)
binary: rustc
commit-hash: dfc5add915e8bf4accbb7cf4de00351a7c6126a1
commit-date: 2021-10-13
host: x86_64-pc-windows-msvc
release: 1.57.0-nightly
LLVM version: 13.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.E-needs-mcveCall for participation: This issue has a repro, but needs a Minimal Complete and Verifiable ExampleT-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