我有一个非常大的结构(在堆上和堆栈上),我在函数中使用。大多数时候,我想要该结构的一个简单变量,因为我直接对大结构进行操作。然而,在某一时刻,我被迫(通过函数签名)将此结构传递到切片内部。
struct VeryBig(Vec<String>, [u64; 50]);
fn takes_slice(_: &[VeryBig]) {}
fn main() {
let foo = VeryBig(vec!["Ferris".to_string(); 100], [27; 50]);
// Use `foo` directly a bunch of times
takes_slice(&foo); // <-- mismatched type
// Use `foo` directly a bunch of times
}
这显然并且可以理解地导致了这个错误:
error[E0308]: mismatched types
--> src/main.rs:10:17
|
10 | takes_slice(&foo); // <-- mismatched type
| ^^^^ expected slice, found struct `VeryBig`
|
= note: expected type `&[VeryBig]`
found type `&VeryBig`
所以我想知道:解决这个问题的最佳方法是什么?我could只是做foo
a [VeryBig; 1]
,但这意味着我必须使用foo[0]
在我想直接使用大结构的任何地方——烦人。或者,我可以暂时将大结构放入数组中,调用takes_slice
并再次将其移出数组。但这也不太好。
据我所知,&T
and &[T]
应该具有相同的内存布局(受指点,而不是指针),所以我希望有一种方法可以轻松地将一个重新解释为另一个,但我还没有找到这样的功能。
您可以使用slice::from_ref https://doc.rust-lang.org/stable/std/slice/fn.from_ref.html.
fn from_ref<T>(s: &T) -> &[T]
在你的代码中():
use std::slice;
takes_slice(slice::from_ref(&foo));
对于可变切片,您可以使用slice::from_mut https://doc.rust-lang.org/stable/std/slice/fn.from_mut.html。另请参阅这个问题 https://stackoverflow.com/questions/32939974/can-i-create-a-slice-of-a-single-byte-u8关于那个话题。
See 如何将对任意类型的引用转换为对长度为 1 的数组的引用? https://stackoverflow.com/q/68564481/155423对于数组。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)