美文网首页
初探rust编译器rustc与包管理工具cargo

初探rust编译器rustc与包管理工具cargo

作者: efab4a395f19 | 来源:发表于2020-03-21 20:50 被阅读0次

    在阅读官方rust指导时发现一个有趣的事情,前期一个简单的case使用了rustc编译,而后面介绍了cargo之后,rust文档里就开始使用cargo,而不是使用rustc。
    先看看官方文档里的入门代码;

    use std::io;
    use rand::Rng;
    
    fn main() {
        println!("Guess the number !");
    
        let secret_number = rand::thread_rng().gen_range(1,101);
    
        println!("The secret number is : {}",secret_number);
    
        println!("Please input your guess.");
    
        let mut guess = String::new();
        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");
    
        println!("you guessed:{}",guess);
    }
    

    这段代码使用了第三方库rand,以及rust自带的标准库std;

    使用rustc编译

    rustc main.rs
    error[E0432]: unresolved import `rand`
     --> main.rs:2:5
      |
    2 | use rand::Rng;
      |     ^^^^ maybe a missing crate `rand`?
    
    error[E0433]: failed to resolve: use of undeclared type or module `rand`
     --> main.rs:7:25
      |
    7 |     let secret_number = rand::thread_rng().gen_range(1,101);
      |                         ^^^^ use of undeclared type or module `rand`
    
    error: aborting due to 2 previous errors
    
    Some errors have detailed explanations: E0432, E0433.
    For more information about an error, try `rustc --explain E0432`.
    

    使用cargo编译

    cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `/Users/xxxxx/workcode/rust/gussing_game/target/debug/gussing_game`
    Guess the number !
    The secret number is : 23
    Please input your guess.
    55
    you guessed:55
    

    结论

    可以发现rust自带的编译器rustc在编译时,不会去自动寻找第三方依赖,需要手动指定编译,而通过使用rust推荐的cargo编译时,则会自动去寻找第三方编译,而且编译顺利;

    相关文章

      网友评论

          本文标题:初探rust编译器rustc与包管理工具cargo

          本文链接:https://www.haomeiwen.com/subject/zfnuyhtx.html