Expressing generic traits of types with owned and borrowed versions

I have some Trait Named

trait Named {
    fn name(&self) -> &str;
}

and a struct implementing it

struct Struct {
    name: String
}

impl Named for Struct {
    fn name(&self) -> &str {
        &self.name
    }
}

Now I found out that I need to support different versions of Owned/Borrowed data (like PathBuf and Path)

How can I express this with a generic Trait such that I can have struct

struct StructContainsPathBuf {
    name: PathBuf
}

impl Named<Path> for StructContainsPathBuf {
    fn name(&self) -> &Path {
        &self.name
    }
}

I basically need a way express the following

trait<OwnedType> Named {
    fn named(&self) -> ThisGuyEvaluatesToTheBorrowedVersionOf<OwnedType>; // String->&str, PathBuf->&Path
}

Introducing just the borrowed version &str/Path as type parameter does not work because then you get the compiler trying to copy it which is unintended.
I think it should somehow be possible with Borrowed/ToOwned but I failed trying myself.

I don’t understand this point, would you elaborate? Based on this

I’d just say you do

use std::path::Path;
use std::path::PathBuf;

trait Named<T: ?Sized> {
    fn name(&self) -> &T;
}

struct StructContainsPathBuf {
    name: PathBuf
}

impl Named<Path> for StructContainsPathBuf {
    fn name(&self) -> &Path {
        &self.name
    }
}

(playground)

2 Likes

Thank you for the ?Sized hint

Turns out the problem is not what you are suggesting but some different problem with the borrow checker which I tried to mention here

If you still have a problem, you’ll need to describe it better. As mentioned above, this description of yours you quoted is something I don’t understand, mostly because it’s too vague; you’d need to provide more details, preferably a code example and an error message.

I'll try to either solve it or come up with a MWE

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.