我已经在多个上下文中阅读过“胖指针”一词,但是我不确定它的确切含义以及何时在Rust中使用它。该指针似乎是普通指针的两倍,但我不明白为什么。它也似乎与特征对象有关。
是否可以在数组前面添加一个值?我知道如何连接两个数组,但如果我有一个数组和一个值(与数组类型相同),我可以将此元素添加到数组前面吗?
我读过什么是Rust的确切自动解除引用规则?从头到尾,但我仍然有一个关于从数组到切片的强制的问题.
让我们考虑以下代码:
let arr: &[i32; 5] = &&&[1, 2, 3, 4, 5];
// let arr: &[i32] = &&&[1, 2, 3, 4, 5]; // Error; expected slice, found reference
Run Code Online (Sandbox Code Playgroud)
我希望它&&&[1, 2, 3, 4, 5]有类型,&&&[i32; 5]并且引用 &&[i32; 5]=> &[i32; 5]=> &[i32; 5]=> &[i32],但结果与我的预期不同.
我试着运行以下代码:
let arr: &&&[i32; 5] = &&&[1, 2, 3, 4, 5];
let n = arr.first().unwrap(); // 1
Run Code Online (Sandbox Code Playgroud)
这是正确的代码.arr强制类型为&&&[i32; 5]=> &&[i32; 5]=> &[i32; 5]=> …
我不明白切片和参考之间的区别。&String和 和有&str什么区别?我在网上读到一些东西,说引用是一个细指针,切片是一个胖指针,但我不知道,似乎无法找到这两个的意思。我知道切片可以强制转换为引用,但它是如何做到的?Deref特质是什么?
在下面的代码中我收到错误:
error[E0277]: the size for values of type `[{integer}]` cannot be
known at compilation time at the line `for n in numbers[1..] {`
Run Code Online (Sandbox Code Playgroud)
我四处搜寻,但一无所获。
fn main() {
let mut numbers = Vec::new();
numbers.push(1);
numbers.push(32);
numbers.push(43);
numbers.push(42);
// ... And many more
println!("{:?}", numbers); // Sanity
let mut sum = 0;
// Problem code area
for n in numbers[1..] {
sum = sum + n;
}
// Problem code area
println!("{}", sum);
}
Run Code Online (Sandbox Code Playgroud)
&另外,如果我将它们替换为以下内容(添加和*用于所有权/借用和取消引用),问题行就会起作用
for n in &numbers[1..] …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个带有 的函数T: Into<Vec<u8>>,但是当我尝试将 的数组传递u8给它时,即使From<&'a [T]>>由Vec以下实现,它也不会编译:
the trait `std::convert::From<&[u8; 5]>` is not implemented for `std::vec::Vec<u8>`
Run Code Online (Sandbox Code Playgroud)
这是我的代码
fn is_hello<T: Into<Vec<u8>>>(s: T) {
let bytes = b"hello".to_vec();
assert_eq!(bytes, s.into());
}
fn main() {
is_hello(b"hello");
}
Run Code Online (Sandbox Code Playgroud) 我想在编译时检查实现中使用的切片是否From具有特定大小。
(游乐场)
#[derive(Debug)]
struct Pixel {
r: u8,
g: u8,
b: u8,
}
impl From<&[u8]> for Pixel {
fn from(arr: &[u8]) -> Pixel {
Pixel {
r: arr[0],
g: arr[1],
b: arr[2],
}
}
}
fn main() {
println!("Hello, world!");
let arr: [u8; 9] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let pixels: Vec<Pixel> = arr.chunks_exact(3).map(Pixel::from).collect();
println!("{:.?}", pixels);
}
Run Code Online (Sandbox Code Playgroud)
这并不像我想要的那么具体。我想尽可能清楚地检查arr传递给is 3 个元素(在编译时)。Pixel::from<&[u8]>()
想到了assert!(arr.len()==3),但这在运行时检查。
所以我想也许我可以通过( Playground )进行转换:
impl From<[u8; …Run Code Online (Sandbox Code Playgroud) 我正在尝试将数组传递给函数:
fn my_func(xs: [usize]) -> usize {
0
}
fn main() {
let arr = [329, 457, 657];
let res = my_func(inp);
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
fn my_func(xs: [usize]) -> usize {
0
}
fn main() {
let arr = [329, 457, 657];
let res = my_func(inp);
}
Run Code Online (Sandbox Code Playgroud)
我该如何修复该错误?