在这个例子里,我认为B继承A之后,B就包含了F函数。所以删除了"impl A",在"impl B"中添加了F函数。结果报错说B不包含F。那么B到底继承了什么?而且把继承代码删除,这个示例也正常。
trait A
{
fn f(&self);
}
trait B : A
{
fn t(&self);
}
struct Example
{
first : String,
second : String,
}
impl A for Example
{
fn f(&self)
{
print!("{} ",self.first);
}
}
impl B for Example
{
fn t(&self)
{
print!("{}",self.second);
}
}
fn main()
{
let s = Example{first:String::from("Yiibai"),second:String::from("tutorial")};
s.f();
s.t();
}
1
共 5 条评论, 1 页
评论区
写评论trait实际上是一种限制
这种语法是声明了此trait自动受到那些trait的限制。
正好看到trait的这个章节,trait的继承被称为Subtrait,例如: trait Creature: Visible{
} 那么意思就是所有的creatures都是visible的,任何类型实现了Creature必须实现Visible trait。 Subtrait s就像Java或者C#中的subinterface ,是一种描述trait继承已有trait的方法,增加新的方法。这个例子中适用Creature的方法都可以适用Visible trait。
trait并非继承,而是一种共享行为,即实现了这个trait你也某种共同的行为
对以下内容的回复:
泛型限制:
我的理解是 trait B : A 不是继承 ,而是表示限定trait类型的范围,impl traitB for T , T必须impl traitA