gpt4 book ai didi

rust - 为什么使用外部包装箱的功能需要将依赖特征纳入范围?

转载 作者:行者123 更新时间:2023-11-29 08:33:07 24 4
gpt4 key购买 nike

考虑 official tutorial 中的以下代码

extern crate rand;

use rand::Rng;

fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101);
}

rand::thread_rng().gen_range(1, 101) 这行让我有点困惑,因为我希望自动调用 rand::thread_rng()解决它正在使用的特征的依赖性。

但是我需要 use rand::Rng; 才能工作。

这是否意味着当我想在 3rd 方箱中使用某些功能时,我必须手动解决依赖关系?

最佳答案

Why does using an external crate's function require bringing the dependent trait into scope?

它没有。这编译得很好:

extern crate rand;

fn main() {
let secret_number = rand::thread_rng();
}

然后您将尝试从该函数调用的返回值上的特征调用方法。 要求特征在范围内,如 Why do I need to import a trait to use the methods it defines for a type? 中所述。

关于rust - 为什么使用外部包装箱的功能需要将依赖特征纳入范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45515579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com