在为引用和非引用类型实现一个特性时,我是否必须实现它两次? [英] Do I have to implement a trait twice when implementing it for both reference and non-reference types?
本文介绍了在为引用和非引用类型实现一个特性时,我是否必须实现它两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为引用和非引用类型实现一个特征.我是否必须两次实现这些功能,或者这样做不习惯?
I want to implement a trait for both a for reference and non-reference type. Do I have to implement the functions twice, or this is not idiomatic to do so?
这是演示代码:
struct Bar {}
trait Foo {
fn hi(&self);
}
impl<'a> Foo for &'a Bar {
fn hi(&self) {
print!("hi")
}
}
impl Foo for Bar {
fn hi(&self) {
print!("hi")
}
}
fn main() {
let bar = Bar {};
(&bar).hi();
&bar.hi();
}
推荐答案
这是 借用
特征.
use std::borrow::Borrow;
struct Bar;
trait Foo {
fn hi(&self);
}
impl<B: Borrow<Bar>> Foo for B {
fn hi(&self) {
print!("hi")
}
}
fn main() {
let bar = Bar;
(&bar).hi();
&bar.hi();
}
这篇关于在为引用和非引用类型实现一个特性时,我是否必须实现它两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文