What's is the error? custom Borrow trait


#1

What’s the error?
pub trait Renderable: Borrow {
fn render(&self) -> HTML;
fn borrow(&self) -> &str {
&self.render().0
}
}


#3

Please ask complete questions and do some basic research before asking for help. Your question as stated doesn’t actually include an error message or demonstrate that you spent any time trying to solve the problem on your own before asking for help. If you want someone to invest time into answering your questions, you have to put some time into writing and investigating them first (the more work we have to do, the less likely we are to answer your question).

So, please provide:

  1. A minimal but complete example of the code that’s not compiling. Preferably something we can compile and play with.
  2. A copy of the error message(s) you’re seeing.
  3. What you find confusing about the error messages/what you don’t understand.
  4. Some background on what you’re trying to do if relevant.

#4

When you say pub trait Renderable: Borrow, then it means that in order to implement the trait Renderable, one first needs to (separately) implement the trait Borrow. So having the borrow() function within pub trait Renderable does not have the effect you want – it is adding a borrow function to the Renderable trait in addition to the one in the Borrow trait. Also, std::borrow::Borrow requires a type parameter which you are missing. Here’s a working example:

// Interface

pub trait Renderable: Borrow<str> {
    fn render(&self) -> HTML;
}

// Struct and implementation

struct MyStruct(String);

impl Borrow<str> for MyStruct {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Renderable for MyStruct {
    fn render(&self) -> HTML {
        // your implementation
    }
}

(Playground)

Also, if you’re interested in Borrow, you might also be interested in AsRef and Deref.