reference - 如何将引用元组转换为元组的引用?

标签 reference rust

我想将引用元组(它们都是对同一结构成员的引用)转换为元组引用。

我曾尝试以各种方式胁迫他们,但如果不进行克隆,我就做不到。

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/

相关文章:

Java 方法重写 - 访问父类中的方法 - 这可能吗?

java - 如何在 Eclipse 的工作区中查找对 equals() 的类型特定引用?

rust - 如何使用 Rust 中的 C typedef 结构和该结构的函数?

rust - 为什么用 `box` 语法装箱函数指针数组只适用于临时 `let` 绑定(bind)?

multithreading - 运行可中断的 Rust 程序来生成线程

c# - C#中,多个容器中的同一个字符串是否指向同一个位置

c++ - 声明对指针指向值的引用的开销

c++ - "std::string"或 "const std::string&"参数? (参数在内部被复制和修改)

rust - 猜谜游戏,阴影猜测绑定(bind)时出错

performance - 我过滤质数的代码的哪一部分导致它在处理时变慢?