我正在尝试编写一个涉及过滤和折叠数组的程序.我一直在使用The Rust Programming Language,第一版作为参考,但我不明白当我在数组上形成迭代器时会发生什么.这是一个例子:
fn compiles() {
let range = (1..6);
let range_iter = range.into_iter();
range_iter.filter(|&x| x == 2);
}
fn does_not_compile() {
let array = [1, 4, 3, 2, 2];
let array_iter = array.into_iter();
//13:34 error: the trait `core::cmp::PartialEq<_>` is not implemented for the type `&_` [E0277]
array_iter.filter(|&x| x == 2);
}
fn janky_workaround() {
let array = [1, 4, 3, 2, 2];
let array_iter = array.into_iter();
// Note the dereference in the lambda body
array_iter.filter(|&x| …Run Code Online (Sandbox Code Playgroud) 我需要检查组成字符的字节。我知道可以通过从 achar到 aString到 a 来做到这一点&[u8],如下所示:
let multi_byte_char = \'\xc3\xa1\';\nlet little_string = multi_byte_char.to_string();\nlet byte_slice = little_string.as_bytes();\n\nfor byte in byte_slice {\n println!("{}", byte); // Prints "195, 161"\n}\nRun Code Online (Sandbox Code Playgroud)\n\n有没有办法直接从 a 转到chara &[u8]?我在char 文档中找不到任何内容。另一种选择是mem::transmute从 achar到 a [u8; 4],但在这里使用不安全的代码似乎很愚蠢。
编辑:上有一个不稳定的encode_utf8方法char。
rust ×2