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/53798224/

相关文章:

c# - 过滤器列表 : get only unique elements in objects

JavaScript 属性访问 : dot notation vs. 括号?

syntax - 如何在Julia中声明向量的向量

syntax - 我可以使用传递给组件的变量设置 slim 样式的 css 属性值吗

rust - 使用特征作为类型参数时借用检查器失败

rust - 枚举变体的通用向下转型

正确地从函数传递数组

rust - `as` 表达式只能用于原始类型之间的转换,或者,如何将 +1 添加到泛型 T

rust - 无法创建将 byte slice 段转换为整数的通用函数,因为在编译时不知道大小

rust - 如何声明一个静态向量数组?