我正在http://aml3.github.io/RustTutorial/html/01.html处理Rust教程,目前我处理的是Collatz问题。当我尝试编译此代码时,出现错误:
main.rs:9:26: 9:39 error: mismatched types: expected `&str`, found `collections::string::String` (expected &-ptr, found struct collections::string::String)
main.rs:9 let i = from_str::<int>(os::args()[1]).unwrap();
所以,我试图将命令行输入中给出的字符串转换为int
,但命令行的输入是&str
?这里有什么不匹配?
use std::os;
fn main() {
if os::args().len() < 2 {
println!("Error: Please provide a number as argument.");
return;
}
let i = from_str::<int>(os::args()[1]).unwrap();
println!("{:d} has {:d} Collatz steps", i, collatz(i));
}
fn collatz(N: int) -> int {
if N == 1 { return 0; }
match N % 2 {
0 => { 1 + collatz(N/2) }
_ => { 1 + collatz(N*3+1) }
}
}
答案 0 :(得分:3)
该教程陈述:
2014年春季
这是Rust-land的坏消息。直到最近,语言正在经历许多结构性变化。然而,自1.0.0 beta以来,语言已经稳定下来。
所以,这是固定的例子:
use std::env; // env, not os
fn main() {
// args is an iterator now
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Error: Please provide a number as argument.");
return;
}
// int doesn't exist anymore, from_str is better as `parse`
let i: i32 = args[1].parse().unwrap();
// No more `d` specifier
println!("{} has {} Collatz steps", i, collatz(i));
}
// variables should be snake_case
fn collatz(n: i32) -> i32 {
if n == 1 { return 0; }
match n % 2 {
0 => { 1 + collatz(n/2) }
_ => { 1 + collatz(n*3+1) }
}
}
我建议其中一个