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

编程入门 行业动态 更新时间:2024-10-27 08:27:45
本文介绍了是否有在类似结构之间移动字段的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个很大的结构 Foo,并且想将它 map 到一个 Foo 中,其中大部分字段不需要更新.我希望为此使用 .. 运算符,但这是一个类型错误,因为它们在技术上是不同的类型.

I have a big struct Foo<Q>, and want to map it into a Foo<R> where most of the fields don't need updating. I was hoping to use the .. operator for this, but it is a type error, as they are technically different types.

也就是说,给定:

struct Foo<T> { a: usize, b: usize, t: T, } let q: Foo<Q>;

我想写:

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

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

But, this gives me a type error:

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

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

The type error is reasonable, as the types can be thought of as templates in this case.

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

The only workaround I have is to write out the transformation in full, which gets ugly quite quickly:

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

这是一个带有完整测试用例的游乐场,包括编译错误和长格式.

Here's a playground with a full test-case, including the compile error and the long-form.

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

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

推荐答案

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

Is there syntax for moving fields between similar structs?

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

No. There is no such syntax. The current implementation of "struct update" (previously called "functional record update") syntax only allows the exact same type.

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

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

没有.我唯一的建议是解构原始结构,然后重新创建它.您也不需要 ::<R> ,因为它是推断出来的.

No. The only suggestion I have is to destructure your original struct and then recreate it. You also don't need the ::<R> as it's inferred.

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

另见:

  • RFC 2528 — 类型更改结构更新语法
  • 问题 #47741 — 结构初始值设定项 ..x 语法应该适用于具有结构相同的字段子集的其他结构
  • 类似问题:结构更新语法不同类型
  • RFC 2528 — Type-changing struct update syntax
  • Issue #47741 — Struct initializer ..x syntax should work for other structs with structurally equal subset of fields
  • Similar issue: Struct update syntax for different types

更多推荐

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

本文发布于:2023-07-16 23:10:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1126894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   语法   类似   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!