【发布时间】:2014-12-01 20:34:12
【问题描述】:
在 while 循环中重新绑定可变变量是否有效?我无法让以下简单的解析器代码工作。我的意图是在将字符从数组前面复制出来时,用逐渐变短的切片替换新闻切片绑定。
/// Test if a char is an ASCII digit
fn is_digit(c:u8) -> bool {
match c {
30|31|32|33|34|35|36|37|38|39 => true,
_ => false
}
}
/// Parse an integer from the front of an ascii string,
/// and return it along with the remainder of the string
fn parse_int(s:&[u8]) -> (u32, &[u8]) {
use std::str;
assert!(s.len()>0);
let mut newslice = s; // bytecopy of the fat pointer?
let mut n:Vec<u8> = vec![];
// Pull the leading digits into a separate array
while newslice.len()>0 && is_digit(newslice[0])
{
n.push(newslice[0]);
newslice = newslice.slice(1,newslice.len()-1);
//newslice = newslice[1..];
}
match from_str::<u32>(str::from_utf8(newslice).unwrap()) {
Some(i) => (i,newslice),
None => panic!("Could not convert string to int. Corrupted pgm file?"),
}
}
fn main(){
let s:&[u8] = b"12345";
assert!(s.len()==5);
let (i,newslice) = parse_int(s);
assert!(i==12345);
println!("length of returned slice: {}",newslice.len());
assert!(newslice.len()==0);
}
parse_int 未能返回比我传入的切片更小的切片:
length of returned slice: 5
task '<main>' panicked at 'assertion failed: newslice.len() == 0', <anon>:37
playpen: application terminated with error code 101
【问题讨论】:
-
is_digit可以写成c >= b'0' && c <= b'9',顺便说一句。 -
对,我希望这整个代码块如果还没有被标准库淘汰的话。我正在学习,并避免像瘟疫这样的外部依赖,直到 1.0。
标签: while-loop rust slice