Rust未使用的导入:`rand::Rng`和结构体`ThreadRng`中未找到名为`gen_range`的方法。

huangapple go评论79阅读模式
英文:

Rust unused import: `rand::Rng` and no method named `gen_range` found for struct `ThreadRng`

问题

以下是翻译好的内容:

我对Rust还很陌生。我正在尝试学习Rust中模块系统的工作原理,我尝试在文件的顶部像在Node.js或Python中一样导入randio。但是当我尝试在顶部导入randio时,我收到了以下错误消息:
unused import: rand::Rngno method named gen_range found for struct ThreadRng 错误。

帮助

有人能解释一下,我如何像上面的错误示例中使用use关键字以及问题的实质是什么吗?

我的猜测

由于我有JS和Python的经验,我猜想这与变量的作用域有关。但作用域的性质完全不同。所以有人能解释一下错误的原因是什么吗?

以下是两个代码示例。

有问题的代码:


use rand::Rng;
use std::io;

pub mod guess_game{
    
    pub fn start(){
        
        let random_generated_number = rand::thread_rng().gen_range(1, 10);  
        // 错误出现在这里      ---------        ^ no method named `gen_range` found for struct `ThreadRng` in the current scope
items from traits can only be used if the trait is in scope

        let mut user_input = String::new();
        
        println!("Enter a number: ");
    
        io::stdin()
//      ^ a builtin type with a similar name exists: `i8`rustc E0433
            .read_line(&mut user_input)
            .expect("Error ayo hai ta");
    
        let user_input_number:i32 = user_input.trim().parse().expect("Invalid integer provided");
    
        println!("I see you entered {}", user_input);
    
        if user_input_number == random_generated_number {
            println!("RIGHT, You guessed it, {}", random_generated_number);
        }else{
            println!("WRONG!, You will have to guess {}", random_generated_number);
        };
    }
}

正确的代码

pub mod guess_game{

    use rand::Rng;
    use std::io;

    pub fn start(){
        
        let random_generated_number = rand::thread_rng().gen_range(1, 10);  
    
        let mut user_input = String::new();
        
        println!("Enter a number: ");
    
        io::stdin()
            .read_line(&mut user_input)
            .expect("Error ayo hai ta");
    
        let user_input_number:i32 = user_input.trim().parse().expect("Invalid integer provided");
    
        println!("I see you entered {}", user_input);
    
        if user_input_number == random_generated_number {
            println!("RIGHT, You guessed it, {}", random_generated_number);
        }else{
            println!("WRONG!, You will have to guess {}", random_generated_number);
        };
    }
}
英文:

I am new to rust. I am trying to learn how modular system works in rust and I tried to import rand and io at the top line of the file like I would have in nodejs or python. But when I tried to import the rand and io on top, I was getting the error as:
unused import: rand::Rng and no method named gen_range found for struct ThreadRng errors.

Help

Can anyone explain me, how can I work the use keyword as above like in the bugy code and what is the issue really about?

Guessed it

As I have experience in JS and python, I guessed it was related about something with the scoping of variables. But the nature of scoping is completely different. So can anyone explain to me what was the reason of the error.

Here are two codes.

Buggy Code:


use rand::Rng;
use std::io;

pub mod guess_game{
    
    pub fn start(){
        
        let random_generated_number = rand::thread_rng().gen_range(1, 10);  
        // Error was here      ---------        ^ no method named `gen_range` found for struct `ThreadRng` in the current scope
items from traits can only be used if the trait is in scope

        let mut user_input = String::new();
        
        println!("Enter a number: ");
    
        io::stdin()
//      ^ a builtin type with a similar name exists: `i8`rustc E0433
            .read_line(&mut user_input)
            .expect("Error ayo hai ta");
    
        let user_input_number:i32 = user_input.trim().parse().expect("Invalid integer provided");
    
        println!("I see you entered {}", user_input);
    
        if user_input_number == random_generated_number {
            println!("RIGHT, You guessed it, {}", random_generated_number);
        }else{
            println!("WRONG!, You will have to guess {}", random_generated_number);
        };
    }
}

Working code

pub mod guess_game{

    use rand::Rng;
    use std::io;

    pub fn start(){
        
        let random_generated_number = rand::thread_rng().gen_range(1, 10);  
    
        let mut user_input = String::new();
        
        println!("Enter a number: ");
    
        io::stdin()
            .read_line(&mut user_input)
            .expect("Error ayo hai ta");
    
        let user_input_number:i32 = user_input.trim().parse().expect("Invalid integer provided");
    
        println!("I see you entered {}", user_input);
    
        if user_input_number == random_generated_number {
            println!("RIGHT, You guessed it, {}", random_generated_number);
        }else{
            println!("WRONG!, You will have to guess {}", random_generated_number);
        };
    }
}

答案1

得分: 3

Modules do not have lexical visibility.

While Rust lets you create nested modules without creating new files the semantics don't change. That is, by design

mod foo {
    // content here
}

and

mod foo;
// foo.rs
// content here

have exactly the same behavior, intentionally: it makes the implementation simpler, and lets you break up files by moving contents from nested modules into external files, and nothing more.

That means exactly as in Python, for one module to see the contents of another, you need some sort of cross-module import.

So your original code is exactly the same as:

// mod.rs 

use rand::Rng;
use std::io;

pub mod guess_game;
// guess_game.rs
pub fn start(){
    ...
}

which in Python translates to:

# __init__.py
import random
import io

from . import guess_game
# guess_game.py
def start():
    # uses random and io

Do you expect that to work? No? There's your answer.

英文:

> I am new to rust. I am trying to learn how modular system works in rust and I tried to import rand and io at the top line of the file like I would have in nodejs or python [...] Can anyone explain me, how can I work the use keyword as above like in the bugy code and what is the issue really about?

Modules do not have lexical visibility.

While Rust lets you create nested modules without creating new files the semantics don't change. That is, by design

mod foo {
    // content here
}

and

mod foo;
// foo.rs
// content here

have exactly the same behaviour, intentionally: it makes the implementation simpler, and lets you break up files by moving contents from nested modules into external files, and nothing more.

That means exactly as in Python, for one module to see the contents of an other, you need some sort of cross-module import.

So your original code is exactly the same as:

// mod.rs 

use rand::Rng;
use std::io;

pub mod guess_game;
// guess_game.rs
pub fn start(){
    ...
}

which in Python translates to:

# __init__.py
import random
import io

from . import guess_game
# guess_game.py
def start():
    # uses random and io

Do you expect that to work? No? There's your answer.

huangapple
  • 本文由 发表于 2023年4月17日 19:08:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定