How does one implement `ToOwned` for a wrapper of a reference?

⚓ rust    📅 2025-06-07    👤 surdeus    👁️ 3      

surdeus

I have a type that looks like this:

#[derive(Debug, Copy, Clone)]
pub enum Block<'a> {
    // ...
}

It implements both Copy and Clone because all it holds inside is references.

What I now want to add is this:

#[derive(Debug, Clone)]
pub enum OwnedBlock {
    // ...
}

impl<'a> ToOwned for Block<'a> {
    type Owned = OwnedBlock;

    fn to_owned(&self) -> Self::Owned {
        OwnedBlock::from_block(*self)
    }
}

Block here is like a str and OwnedBlock is like String.

But turns out alloc already provides an impl that conflicts with this:

error[E0119]: conflicting implementations of trait `alloc::borrow::ToOwned` for type `block::Block<'_>`
   --> src/block.rs:472:1
    |
472 | impl<'a> ToOwned for Block<'a> {
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: conflicting implementation in crate `alloc`:
            - impl<T> alloc::borrow::ToOwned for T
              where T: core::clone::Clone;

I understand why the default impl might seem to be useful, but it isn't for me here.

I'm okay with usage of nightly-only features.

2 posts - 2 participants

Read full topic

🏷️ rust_feed