Defining a trait with associated type and fn returning Result?

⚓ Rust    📅 2025-06-23    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 50 days ago. The information described in this article may have changed.

A beginner Rustacean here.
I wanted to define a trait like this, which I want to implement for multiple types:

trait AsfaloadKeyPairB {
    type KeyErr;
    fn new(pw: &str) -> Result<Self, Self::KeyErr>;
    fn save(&self, p: Path) -> &Self;
}

but it gives the error

the size for values of type `Self` cannot be known at compilation time
doesn't have a size known at compile-time [E0277]

Running rustc --explain E0277 gives me explanation about types not implementing a trait, which seems not related to my problem. So I try to define the trait differently:

trait AsfaloadKeyPair<'a> {
    type KeyErr;
    fn new(pw: &str) -> Result<&'a Self, Self::KeyErr>;
    fn save(&self, p: Path) -> &Self;
}

This trait definition is accepted, but now I don't know how to implemented...

impl<'a> AsfaloadKeyPair<'a> for minisign::KeyPair {
    type KeyErr = errs::KeyError;
    fn new(password: &str) -> Result<&'a Self, errs::KeyError> {
        let kp = KeyPair::generate_encrypted_keypair(Some(password.to_string()))?;
        Ok(&kp)
    }

I understand why this is not accepted, but I don't see how to fix it. My trait function needs to return a reference, but in my function implementation I can't because it is created locally.
What's the right solution in this situation?

Thanks in advance!

3 posts - 2 participants

Read full topic

🏷️ rust_feed