如何包装另一种类型并向其添加字段和方法? [英] How can I wrap another type and add fields and methods to it?
问题描述
我知道继承在 Rust 世界中是一个坏词,但是必须有某种方式,给定以下结构
I know inheritance is a bad word in the Rust world, however there must be some way, given the following struct
struct Glyph {
// Fields
}
拥有一个新的 Glyphs
结构,它是 Vec
方法(push
等)以及字段的包装器和适合自己的方法?
to have a new Glyphs
struct that is a wrapper for Vec<Glyph>
methods (push
, etc.) as well as fields and methods proper to itself?
推荐答案
您可以定义类型别名(即同义词):
You can define a type alias (i.e. a synonym):
type Glyphs = Vec<Glyph>;
它不是一个独特的类型,因此您可以将 Glyphs
传递给任何需要兼容 Vec
的函数,包括泛型函数.
It is not a distinct type, so you can pass a Glyphs
to any function that expects a compatible Vec
, including generic functions.
您将无法直接向此类型添加字段或固有方法.但是,您可以做的是定义一个扩展特征(即,存在的特征的唯一目的是向您未定义的类型添加方法;对此没有特殊语法)并具有 Glyphs
实施它.如果您使用模块,则必须使用 use
导入特征以将方法引入作用域.
You will not be able to add fields or inherent methods to this type directly. What you can do, though, is define an extension trait (i.e. a trait that exists for the sole purpose of adding methods to a type you didn't define; there's no special syntax for this) and have Glyphs
implement it. If you use modules, you'll have to import the trait with use
to bring the methods into scope.
trait GlyphsExt {
fn x(&self); // define extension method
}
impl GlyphsExt for Glyphs {
fn x(&self) {
// implement method here
}
}
这篇关于如何包装另一种类型并向其添加字段和方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!