我几天前开始涉足 Rust,遇到了以下问题:我发现了 a library这允许我将字体轮廓转换为 SVG;在用户端,部分代码如下所示;
请注意,我在此处添加了一个常量 SCALE
,该常量不存在于所述库附带的原始示例代码中:
const SCALE: f32 = 0.5;
struct Builder<'a>(&'a mut svgtypes::Path);
impl ttf::OutlineBuilder for Builder<'_> {
fn move_to( &mut self, x: f32, y: f32 ) { self.0.push_move_to(
( x * SCALE ) as f64,
( y * SCALE ) as f64 ); }
... }
...
let mut builder = Builder(path_buf);
builder
对象然后被传递给一个函数,该函数执行繁重的工作并回调到实现的方法中。到目前为止,一切顺利:我想缩放路径,上面的代码就是这样做的。但就目前而言,我需要定义一个 const
来做到这一点,因为 Rust 不允许方法引用外部值。但是,我想根据相关字体的属性使缩放因子动态化。
现在,比方说,在 JavaScript 中,我可能会使用一个带有闭包的工厂函数来完成 scale
,或者可以只向标识为 self 的对象添加一个属性
——在脚本语言中有很多方法可以解决这个问题。以上在 Rust 中似乎都不是直截了当的。是否可以声明一种接受附加参数的新结构,如
struct Builder<'a>(&'a mut svgtypes::Path, scale: f32 );
impl ttf::OutlineBuilder for Builder<'_> {
fn move_to( &mut self, x: f32, y: f32 ) { self.0.push_move_to(
( x * self.scale ) as f64,
( y * self.scale ) as f64 ); }
... }
?不用说,上面的代码不会编译。
最佳答案
Would it be possible to perhaps declare a new kind of structure that accepts an additional parameter
是的,会的!示例代码将 Builder
定义为 Tuple Struct ,有点像具有未命名字段的结构。虽然您可以向其中添加另一个元素,您可以将其称为 self.1
,但最好切换到普通结构:
struct Builder<'a> {
path: &'a svgtypes::Path,
scale: f32
};
然后你可以通过 self.scale
访问比例:
impl ttf::OutlineBuilder for Builder<'_> {
fn move_to( &mut self, x: f32, y: f32 ) { self.path.push_move_to(
( x * self.scale ) as f64,
( y * self.scale ) as f64 ); }
... }
关于struct - rust:如何使用引用外部值的回调编写 `impl`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582117/