Rust Trait std::borrow::Borrow与Trait std::convert::AsRef

49 阅读1分钟

Borrow有两个方面

实现Borrow接口

doc.rust-lang.org/std/borrow/…

然后又需要接收Borrow接口的函数(一般自己实现)

fn check<T: Borrow<str>>(s: T) {
    assert_eq!("Hello", s.borrow());
}

约定:

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

说白了没有什么魔法