syntax - 是否有在相似结构之间移动字段的语法?

标签 syntax rust

我有一个大结构 Foo<Q> ,并想要 map它变成了Foo<R>大多数字段不需要更新。我希望使用 ..运算符,但这是一个类型错误,因为它们在技术上是不同的类型。

即给定:

struct Foo<T> {
    a: usize,
    b: usize,
    t: T,
}

let q: Foo<Q>;

我想写:

let r = Foo::<R> {
    t: fixup(q.t),
    ..q
};

但是,这给了我一个类型错误:

error[E0308]: mismatched types
   |
 3 |         ..q
   |           ^ expected struct `R`, found struct `Q`
   |
   = note: expected type `Foo<R>`
              found type `Foo<Q>`

类型错误是合理的,因为在这种情况下可以将类型视为模板。

我唯一的解决方法是完整地写出转换,这很快就会变得很丑陋:

let r = Foo::<R> {
    a: q.a,
    b: q.b,
    t: fixup(q.t),
};

这是 a playground with a full test-case ,包括编译错误和长格式。


在某个地方是否有更好的语法,或者有更好的方法来实现这些 map -类似非平凡结构的方法?

最佳答案

Is there syntax for moving fields between similar structs?

没有。没有这样的语法。 “结构更新”(以前称为“功能记录更新”)语法的当前实现只允许完全相同的类型。

Is there better syntax for this somewhere, or a better way to implement these map-like methods for non-trivial structs?

没有。我唯一的建议是解构您的原始结构,然后重新创建它。您也不需要 ::<R>据推测。

let Foo { a, b, c, d, e, t } = q;
let r = Foo {
    a,
    b,
    c,
    d,
    e,
    t: fixup(t),
};

另见:

关于syntax - 是否有在相似结构之间移动字段的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56417562/

相关文章:

syntax - 如何在 VHDL 中对整数进行按位与运算?

asynchronous - 从 Tokio 应用程序使用 Actix:混合 actix_web::main 和 tokio::main?

callback - Rust 中的惯用回调

rust - 如何在 Rust 的同一个 lib.rs 文件中的测试中引用常量?

rust - 特征类型不匹配,解决了 `<Button as Render>::Props == AppProps`

casting - 如何将 Vec<&mut T> 转换为 Vec<&T>?

php - 复杂子计算的MySQL语法

typescript - 如何从命令行检查 TypeScript 代码的语法错误?

python - 语法错误: unexpected EOF while parsing input commands

swift - _ : vs _ String: when writing functions 的区别/用例是什么