您现在可以定义一个特征,它由一组必需的方法原型组成。结构体可以通过实现这些方法来符合该特征。这使您可以编写适用于符合给定特征的任何结构的通用函数。
特征是用trait关键字声明的。特征的主体应包含用...其主体声明的方法签名。尚不支持默认方法实现。
trait SomeTrait:
fn required_method(self, x: Int): ...
该特征可以通过继承结构来实现。
struct SomeStruct(SomeTrait):
fn required_method(self, x: Int):
print("hello traits", x)
然后,您可以编写一个通用函数来接受任何符合该特征的类型。您可以通过使用特征类型参数创建参数化函数来实现此目的:
fn fun_with_traits[T: SomeTrait](x: T):
x.required_method(42)
可以使用符合该特征的类型实例来调用它:
var thing = SomeStruct()
# Infer the parameter `T`!
fun_with_traits(thing)
特征还可以从其他特征继承,这仅要求子特征的实现者也符合所有父特征。
trait Parent:
fn parent_func(self): ...
trait Child(Parent):
fn child_func(self): ...
然后,可以在 Trait 的实例上调用子特征和父特征方法Child。同样,子特征的实例可以转换为父特征的实例。
fn the_parents[T: Parent](x: T):
x.parent_func()
fn the_children[T: Child](x: T):
x.child_func()
x.parent_func()
# Upcast `x` from instance of `Child` to `Parent`.
the_parents(x)
Destructable该语言添加了一个基本特征。这是每个特征都会自动遵守的核心特征。这使得可以销毁泛型类型和泛型集合。
注意:我们知道这个特质可能拼写得更好Destructible。我们计划在将来删除它,并将其功能转移到AnyType任何不提供自己的析构函数的类型将有一个默认的、无操作的析构函数。
我们在标准库中添加了一些特征,您可以在自己的类型上实现这些特征:
Destructable
Copyable
Movable
Stringable
Intable
Sized
CollectionElement
我们添加了内置len()、str()和int()函数,它们分别与实现Sized、Stringable和Intable特征的类型一起使用。
DynamicVector现在是一个适当的泛型集合,可以使用任何实现Movable和Copyable特征的类型。这意味着您现在可以编写,例如,DynamicVector[String]. 另外,DynamicVector现在在销毁时调用其元素析构函数,因此_del_old已被删除。
printStringable现在适用于通过调用其方法实现的任何类型str:
@value
struct BoxedInt(Stringable):
var value: Int
fn __str__(self) -> String:
return self.value
print(BoxedInt(11), "hello traits!", BoxedInt(42))