Is there derive macro for Borrow trait?

⚓ Rust    📅 2025-10-18    👤 surdeus    👁️ 2      

surdeus

Below are from std documentation:

In particular Eq, Ord and Hash must be equivalent for borrowed and owned values:
x.borrow() == y.borrow() should give the same result as x == y.

If I understand correctly, such code should be writing when impl Borrow for Baz, one of whose fields is T:

struct Baz {
    key: String,
    // other fields are omitted
}

impl Borrow<str> for Baz {
    fn borrow(&self) -> &str {
        self.key.as_str()
    }
}

// > In particular Eq, Ord and Hash must be equivalent for borrowed and owned values:
// > x.borrow() == y.borrow() should give the same result as x == y.

impl Hash for Baz {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.key.hash(state);
    }
}

impl PartialEq for Baz {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl Eq for Baz {}

impl PartialOrd for Baz {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Baz {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.key.cmp(&other.key)
    }
}

(This is useful when we need HashMap<&str, Baz>, and &str key ref to baz.key. This self-referential struct can be avoided by HashSet with special Borrow and Hash implemented)

I wonder if there are crates to simplify Borrow trait implementation like this with derive macros.

1 post - 1 participant

Read full topic

🏷️ Rust_feed