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),
};
也可以看看:
  • RFC 2528 — Type-changing struct update syntax
  • Issue #47741 — Struct initializer ..x syntax should work for other structs with structurally equal subset of fields
  • 类似的问题:Struct update syntax for different types
  • 关于syntax - 是否存在在类似结构之间移动字段的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64793844/

    相关文章:

    Rust 示例 : The ref pattern

    json - 使用Serde反序列化嵌套JSON结构时的“invalid type: map, expected a sequence”

    rust - 如何借用一个展开的 Option<T>?

    r - 从向量中有效地删除 n 个随机条目,其中 n 可能为 0

    触发器中的 MySql 错误语法

    JavaScript "x in obj": obj. x 未定义?

    rust - 如何在impl中使用struct?

    syntax - PHP类方法中使用的 undefined variable 没有错误

    python - SyntaxError 无效 token

    rust - 我如何绑定(bind) Higher Rank Trait Bound 生命周期?