我有一个大的结构Foo Q,并且想要将它映射到Foo R其中大多数字段不需要更新.我希望使用..运算符,但这是一个类型错误,因为它们在技术上是不同的类型. 那是,给定: struct FooT { a: usize, b
那是,给定:
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,包括编译错误和长格式.
这个地方有更好的语法,或者为非平凡结构实现这些类似地图的方法的更好方法吗?
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),
};
也可以看看:
> Pre-RFC 1975:Support type transformations in FRU (functional record update) syntax
> Struct initializer ..x syntax should work for other structs with structurally equal subset of fields (issue #47741)
>类似问题:Struct update syntax for different types
