我想将引用元组(它们都是对同一结构成员的引用)转换为元组引用。
我曾尝试以各种方式胁迫他们,但如果不进行克隆,我就做不到。
struct Bar();
struct Foo(Bar, Bar, Bar);
fn main() {
let a: &Foo = &Foo(Bar(), Bar(), Bar());
let b: &(Bar, Bar) = &(a.0, a.1);
}
error[E0507]: cannot move out of borrowed content
--> src/main.rs:7:28
|
7 | let b: &(Bar, Bar) = &(a.0, a.1);
| ^^^ cannot move out of borrowed content
error[E0507]: cannot move out of borrowed content
--> src/main.rs:7:33
|
7 | let b: &(Bar, Bar) = &(a.0, a.1);
| ^^^ cannot move out of borrowed content
我希望 b
是 &(Bar, Bar)
类型,因为 a
是 &Foo
类型.
最佳答案
这是不可能的。
引用引用一个值。您希望有一个 &(Bar, Bar)
但内存中没有任何地方有 (Bar, Bar)
的二元组。你不能引用不存在的东西。
&(A, B)
和 (&A, &B)
的内存布局根本不兼容,因此您也不能使用不安全的 Rust 技术。
在这种特殊情况中,您可能可以使用不安全的 Rust 将您的 &Foo
直接转换为 &(Bar , 栏)
, 但是...
- 要求元组结构和元组的布局相同;我不知道这是有保证的1
- 它要求元组结构的布局紧密打包,以便您可以通过成员大小进行偏移以到达下一个;我不知道这是有保证的1
- 它要求元组结构的布局按照定义的相同顺序放置成员;我不知道这是有保证的1
- 你只能对顺序片段进行;没有得到第一和第三项
// I copied this unsafe block from Stack Overflow
// without properly documenting why I think this code is safe.
let b: &(Bar, Bar) = unsafe { &*(a as *const Foo as *const (Bar, Bar)) };
println!("{:?}", b);
// I copied this unsafe block from Stack Overflow
// without properly documenting why I think this code is safe.
let c: &(Bar, Bar) = unsafe {
let p = a as *const Foo as *const Bar;
let p = p.offset(1);
&*(p as *const (Bar, Bar))
};
println!("{:?}", c);
1 — 事实上,reference explicitly states :
Tuples do not have any guarantees about their layout.
The exception to this is the unit tuple (
()
) which is guaranteed as a zero-sized type to have a size of 0 and an alignment of 1.
这意味着虽然此代码可能会打印出您所期望的内容并且 Miri 不会提示,但这是未定义的行为。
关于reference - 如何将引用元组转换为元组的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528652/