简体   繁体   中英

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. 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 ? 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

Which is bad news in Rust-land. Until very recently, the language was undergoing many structural changes. Since the 1.0.0 betas however, the language has stabilized greatly.

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
  3. Fix the examples and submit them back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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