我在API的某个地方使用了一个带有&[&A]参数的函数,但只有一个A对象向量。当我尝试通过以下语法使用此功能时
pub struct A(pub u64);
fn test(a: &[&A]){}
fn main() {
let v = vec![A(1), A(2), A(3)];
let a = &v[..];
test(a);
}
Run Code Online (Sandbox Code Playgroud)
我有一个错误:
<anon>:12:9: 12:10 error: mismatched types:
expected `&[&A]`,
found `&[A]`
(expected &-ptr,
found struct `A`) [E0308]
Run Code Online (Sandbox Code Playgroud)
我做了一些尝试,但没有成功:
let a = &v[&..]
Run Code Online (Sandbox Code Playgroud)
和
let a = &v[&A]
Run Code Online (Sandbox Code Playgroud)
我怎样才能让&[&A]从Vec<A>?
简短的答案:您不能。这些类型彼此不兼容。
如果这确实是API所需要的,该怎么办
test(&v.iter().collect::<Vec<_>>());
Run Code Online (Sandbox Code Playgroud)
但这分配了一个新的向量。如果您是API的作者,请考虑更改它:&[&T]是一种奇怪的类型,因为您需要切片和其中的对象使用不同的所有者。&[T]已经具有内部对象的按引用传递语义。
| 归档时间: |
|
| 查看次数: |
1402 次 |
| 最近记录: |