为什么这个 rand use 语句在 rust 中有效?
Why does this rand use statement work in rust?
按照 Rust 书中的示例使用建议的 rand = "0.6.0"
,我得到的代码如下所示:
use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
}
本书后面关于模块的章节中所说的一切都表明,如果你像上面那样做 use rand::Rng;
,你将能够使用 Rng
。如果这恰好是一个模块本身,您可以使用带有 Rng::submodule
的子模块。如果那恰好是一种类型,您只需将其用作 Rng
。然而,在上面的代码中,我们从不在任何地方使用 Rng
。
相反,我们使用看似无关的rand::thread_rng()
。据我了解,由于 rand
是顶级 crate 的名称,我们应该能够使用它,即使没有 use
语句似乎没有做任何事情。
相反,由于某种原因,如果没有 use
语句,程序将无法编译。这真是令人困惑。我希望这本书能更好地解释那里发生的事情。
为什么我们需要use语句?为什么我们不使用 Rng
?它与 rand::thread_rng()
有什么关系?
我来自 Python 背景,所以我习惯了这样的想法,即如果你导入 threading
,你就在使用 threading.something
。如果您导入 django.utils
,则您使用的是 django.utils.something
。这似乎是 django.utils
的导入,您在其中使用完全不相关的 django.urls
.
除非特征在范围内,否则不能调用特征方法。
In the code above however, we never use Rng
anywhere.
您正在使用 Rng
. gen_range()
is a trait method defined by the Rng
trait so Rng
must be in scope for you to call gen_range()
。
具体细节:rand::thread_rng()
returns ThreadRng
which implements RngCore
and gets an Rng
implementation because of the generic blanket impl impl<R> Rng for R where R: RngCore + ?Sized
。
按照 Rust 书中的示例使用建议的 rand = "0.6.0"
,我得到的代码如下所示:
use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
}
本书后面关于模块的章节中所说的一切都表明,如果你像上面那样做 use rand::Rng;
,你将能够使用 Rng
。如果这恰好是一个模块本身,您可以使用带有 Rng::submodule
的子模块。如果那恰好是一种类型,您只需将其用作 Rng
。然而,在上面的代码中,我们从不在任何地方使用 Rng
。
相反,我们使用看似无关的rand::thread_rng()
。据我了解,由于 rand
是顶级 crate 的名称,我们应该能够使用它,即使没有 use
语句似乎没有做任何事情。
相反,由于某种原因,如果没有 use
语句,程序将无法编译。这真是令人困惑。我希望这本书能更好地解释那里发生的事情。
为什么我们需要use语句?为什么我们不使用 Rng
?它与 rand::thread_rng()
有什么关系?
我来自 Python 背景,所以我习惯了这样的想法,即如果你导入 threading
,你就在使用 threading.something
。如果您导入 django.utils
,则您使用的是 django.utils.something
。这似乎是 django.utils
的导入,您在其中使用完全不相关的 django.urls
.
除非特征在范围内,否则不能调用特征方法。
In the code above however, we never use
Rng
anywhere.
您正在使用 Rng
. gen_range()
is a trait method defined by the Rng
trait so Rng
must be in scope for you to call gen_range()
。
具体细节:rand::thread_rng()
returns ThreadRng
which implements RngCore
and gets an Rng
implementation because of the generic blanket impl impl<R> Rng for R where R: RngCore + ?Sized
。