简体   繁体   English

从os :: args调用from_str上的字符串时类型不匹配

[英]Mismatched types when calling from_str on a String from os::args

I am working through the Rust tutorial at http://aml3.github.io/RustTutorial/html/01.html , and I am currently on the Collatz problem. 我正在浏览Rust教程http://aml3.github.io/RustTutorial/html/01.html ,目前我正处理Collat​​z问题。 When I try to compile this code, I get an error of: 当我尝试编译此代码时,出现以下错误:

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();                                                                                     

So, I am trying to convert the string given from the command line input into an int , but the input from the command line is a &str ? 所以,我试图将从命令行输入给出的字符串转换为int ,但命令行的输入是&str What is being mismatched here? 这里有什么不匹配的?

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) }
    }
}

That tutorial states: 该教程指出:

Spring 2014 2014年春季

Which is bad news in Rust-land. 哪个是Rust-land的坏消息。 Until very recently, the language was undergoing many structural changes. 直到最近,语言正在经历许多结构性变化。 Since the 1.0.0 betas however, the language has stabilized greatly. 然而,自1.0.0 beta以来,语言已经稳定下来。

So, here's that example fixed: 所以,这是固定的例子:

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) }
    }
}

I'd suggest one of 我建议其中一个

  1. Not using that tutorial anymore 不再使用该教程了
  2. Contact the authors and ask them to label what version of Rust it works with 联系作者并要求他们标记它适用的Rust版本
  3. Fix the examples and submit them back 修复示例并将其提交回来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM