我有一个很大的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),
};
也可以看看:..x
syntax should work for other structs with structurally equal subset of fields 关于syntax - 是否存在在类似结构之间移动字段的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64793844/