Trait¶
类型Trait¶
trait描述了一类类型的特征,要求类型必须实现指定的成员谓词,从而允许实现类似接口类和泛型的功能。
trait的声明¶
使用trait关键字声明一个trait。下面的代码声明了一个名为HasFooBar的trait,要求类型必须实现成员谓词fn foo() -> str和fn bar(int)
使用trait约束基类¶
trait还支持约束类型的基类。注记basetype约束类型的基类。trait ExtendsInt要求类型必须直接或间接地extends int类型,且不是具名继承。
内建trait¶
MirrorQL中有部分内建trait,用于在不兼容的类型之间转换
// int,str,bool,float实现
trait asInt{
fn toInt() -> int;
}
// int,str,bool,float实现
trait asStr{
fn toString() -> str;
}
// int,str,bool,float实现
trait asFloat{
fn toFloat() -> float;
}
实现trait¶
使用impl语法实现trait。
trait TraitFoo{
fn foo() -> str;
}
class One extends int {
fn init(){
self == 1
}
}
// 对于同一个`class`和同一个`trait`,只能有一个`impl`体
impl TraitFoo for One {
fn foo() -> str {
result == "Foo:" + self.toString()
}
}
若class本身已满足trait的要求,可以使用空impl体实现trait
trait TraitFoo{
fn foo() -> str;
}
class One extends int {
fn init(){
self == 1
}
fn foo() -> str {
result == "Foo:" + self.toString()
}
}
// 对于同一个class和同一个trait,只能有一个impl体
impl TraitFoo for One;
Note
只有显式impl后,才认为某个类型实现了trait。
使用trait¶
trait impl体中定义的谓词会被添加到对应class的成员谓词列表中,因此impl体中定义的谓词也可作为成员谓词使用。
trait TraitFoo{
fn foo() -> str;
}
class One extends int {
fn init(){
self == 1
}
}
// 对于同一个class和同一个trait,只能有一个impl体
impl TraitFoo for One {
fn foo() -> str {
result == "Foo:" + self.toString()
}
}
fn main() {
let one:One;
one.foo() == "Foo:1"
}
此外,trait还被用作参数化函数、类、谓词中的类型约束。