rust:如何使用引用外部值的回调编写`impl`

问题描述 投票:-1回答:1

我几天前开始涉足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对象然后传递给执行繁重工作的函数,并回调到实现的方法中。到目前为止,一切都很好:我想缩放路径,上面的代码可以做到这一点。但是,由于Rust不允许方法引用外部值,因此我需要定义一个const来做到这一点。但是,我想根据相关字体的属性使缩放比例动态化。

[现在,在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 ); }
  ... }

?不用说上面的代码不会编译。

struct rust closures
1个回答
2
投票

也许可以声明一种接受附加参数的新型结构

是,会的!示例代码将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 ); }
... }
© www.soinside.com 2019 - 2024. All rights reserved.