rust - 为什么我不能 `.iter()` 字符串切片?

标签 rust

为什么迭代字符串切片是不可能的?

fn main() {
    let text = "abcd";
    for (i, c) in text.iter().enumerate() {
        // ...
    } 
}
给出错误
error[E0599]: no method named `iter` found for reference `&str` in the current scope
 --> src/main.rs:3:24
  |
3 |     for (i, c) in text.iter().enumerate() {
  |                        ^^^^ method not found in `&str`
如何使字符串切片可迭代?

最佳答案

没有.iter()str 定义的方法;也许是因为它可能是模棱两可的。即使在您的问题中,也不清楚您究竟想要迭代什么,字符或字节。

  • .bytes() 将产生原始的 utf-8 编码字节
  • .chars() 将产生 char s,它们是 unicode 标量值
  • 或者 .graphemes() 来自 unicode-segmentation crate 为每个“用户感知的字符”生成子字符串

  • 每个都有很多用例,只需选择最合适的。 Playground
    use unicode_segmentation::UnicodeSegmentation; // 1.8.0
    
    fn main() {
        let text = "🤦🏼‍♂️"; // browser rendering may vary
        println!("{}", text.bytes().count());         // 17
        println!("{}", text.chars().count());         // 5
        println!("{}", text.graphemes(true).count()); // 1
    }
    

    关于rust - 为什么我不能 `.iter()` 字符串切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69504404/

    相关文章:

    Rustc 仅在分配溢出的值时发出警告

    linux - Rust 无法在 Linux 中编译为可执行文件

    linux - 柴油编译卡在Lightsail上

    iterator - Vec<Vec<(K, V)>> 的可变迭代器

    module - 错误[E0277] : the trait bound `my_struct::MyStruct: my_trait::MyTrait` is not satisfied

    rust - 在位图中画一条线(可能用 Piston )

    使用 nom 解析需要先行的文本

    实现多个特征的 Rust 结构体字段

    rust - 如何向编译器解释 T 以返回相同类型的方式实现 Add?

    rust - Rust-从 `&str`转换为 `String`,然后使用闭包转换