rust - "panicked at ' 断言失败 : begin <= end"when using map

标签 rust

我刚刚开始接触 Rust。

fn main() {
    let s = "aaabbb\naaaccc".to_string();
    let a: Vec<&str> = s.split('\n').map(|s| s.slice_chars(3, s.len())).collect();
    assert_eq!(a, vec!["bbb", "ccc"]);
}

虽然上面的代码有效,但这个不行。它死于 map

#![feature(process, collections)]
use std::process::Command;

fn main() {
    let output = Command::new("git").args(&["status", "--porcelain"]).output().unwrap_or_else(|e| {
      panic!("failed to execute process: {}", e)
    });
    let s = String::from_utf8_lossy(output.stdout.as_slice()).to_string();
    let a: Vec<&str> = s.split('\n').map(|s| s.slice_chars(3, s.len())).collect();
}

这些是回溯。

$ RUST_BACKTRACE=1 cargo run
     Running `target/hello_world`
thread '<main>' panicked at 'assertion failed: begin <= end', /Users/rustbuild/src/rust-buildbot/slave/nightly-dist-rustc-mac/build/src/libcore/str/mod.rs:1478
stack backtrace:
   1:        0x1091266b3 - sys::backtrace::write::hc8e3cee73e646c590nC
   2:        0x10912ba0e - panicking::on_panic::h00b47941f5bc8a02HOL
   3:        0x109110de8 - rt::unwind::begin_unwind_inner::h539538ef7f909326UvL
   4:        0x1091115fe - rt::unwind::begin_unwind_fmt::h7ee8242816be0431quL
   5:        0x10912b29e - rust_begin_unwind
   6:        0x10914a487 - panicking::panic_fmt::hbdb6961ecc952cf7cSv
   7:        0x10914a35a - panicking::panic::h2860b801a6212420fQv
   8:        0x10914bfd1 - str::str.StrExt::slice_chars::hb48fc0a9452c1b98PGD
   9:        0x109110791 - str::StrExt::slice_chars::h13298185343564271120
  10:        0x10910fe14 - main::closure.2239
  11:        0x10910fd13 - iter::Map<I, F>::do_map::h17245677587133977247
  12:        0x10910e7dd - iter::Map<I, F>.Iterator::next::h11146527951811133470
  13:        0x10910dc39 - vec::Vec<T>.FromIterator<T>::from_iter::h11956274897938765189
  14:        0x10910d8bf - iter::IteratorExt::collect::h15101737251385262689
  15:        0x109106f22 - main::h2fa2dff98d35cbb8faa
  16:        0x10912d279 - rust_try_inner
  17:        0x10912d266 - rust_try
  18:        0x10912c1f2 - rt::lang_start::h660a0b4ce4c9ac40HIL
  19:        0x109106f9f - main

感谢您的帮助!

$ rustc --version
rustc 1.0.0-nightly (522d09dfe 2015-02-19) (built 2015-02-20)

最佳答案

您超出了字符串的范围。这是一个例子:

fn main() {
    let s = "a";
    let s2 = s.slice_chars(3, s.len());
}

我真的不知道你为什么要进行这种切片,所以很难推荐更好的解决方案。

关于rust - "panicked at ' 断言失败 : begin <= end"when using map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666042/

相关文章:

rust - 使用hyper时如何直接控制http body(大尺寸)?

rust - 不能借用为不可变的,因为它在函数参数中也被借用为可变的

go - 使用什么语言编写游戏库,Go 还是 Rust?

data-structures - 在内存中迭代 HashMap 是如何工作的 : Rust

rust - 为什么 Option<f64> 的大小在 64 位 Linux 上是 16 字节?

rust - 了解循环中的不可变借用

rust - 如何在立即丢弃向量时将值移出向量?

regex - Rob Pikes 正则表达式的惯用 Rust 重写

rust - 有没有办法在 RwLock drop 上运行闭包?

pointers - 如何强制 Rust 获得非安全方法分配的内存的所有权?