rust - Rust 中带有私有(private)类型的显式类型注释

标签 rust tor type-annotation

我想找出 Rust 中变量的类型:

use anyhow::Result;
use arti_client::{TorClient, TorClientConfig};
extern crate tokio;

#[tokio::main]
async fn main() -> Result<()> {
    let config = TorClientConfig::default();
    let tor_client = TorClient::create_bootstrapped(config).await?;

    // What is the type of `tor_client`?

    Ok(())
}

为了找出变量的类型tor_client ,我用了std::any::type_name :

use std::any::type_name;
fn type_of<T>(_: T) -> &'static str {
    type_name::<T>()
}

[...]

println!("{}", type_of(tor_client));

打印到标准输出的类型是 arti_client::client::TorClient<tor_rtcompat::PreferredRuntime> .

我天真地认为我现在可以使用显式类型注释声明变量:

use anyhow::Result;
use arti_client::{TorClient, TorClientConfig};
extern crate tokio;

#[tokio::main]
async fn main() -> Result<()> {
    let config = TorClientConfig::default();
    let tor_client: arti_client::client::TorClient<tor_rtcompat::PreferredRuntime> =
        TorClient::create_bootstrapped(config).await?;
    
    Ok(())
}

但是,编译器绝对不喜欢这样:

error[E0603]: module `client` is private
   --> src/main.rs:52:34
    |
52  |     let tor_client: arti_client::client::TorClient<tor_rtcompat::PreferredRuntime> =
    |                                  ^^^^^^ private module
    |
note: the module `client` is defined here
   --> /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/arti-client-0.3.0/src/lib.rs:220:1
    |
220 | mod client;
    | ^^^^^^^^^^^


error: aborting due to previous error

我做错了什么?我假设arti_client::client模块是私有(private)的是有原因的......

为什么我想找出类型并使用显式类型注释的背景:我想将该变量的引用传递给自定义函数。据我了解,我不能/不应该在不知道类型的情况下声明函数参数。

最佳答案

client模块是私有(private)的,但这并不意味着您无法访问该结构。

要查看要使用的确切类型,您可以检查 documentation对于所讨论的方法;该方法的签名是这样的:

pub async fn create_bootstrapped(config: TorClientConfig) -> Result<Self>

哪里Selfarti_client::TorClient<tor_rtcompat::PreferredRuntime> 的别名.

正如你所看到的,这个类型确实是 TorClient ,如type_name告诉过你了,但它的范围直接在 arti_client 中 crate 根 - 不在 client 中模块。要了解这种差异,让我们检查 source :

mod client;
// skipped
pub use client::{BootstrapBehavior, DormantMode, StreamPrefs, TorClient};

所以:

  • 模块client确实是私有(private)的;
  • struct TorClient在那里定义,这就是 type_name显示;
  • 但它是从 crate 根重新导出的,因此您无需访问私有(private)模块即可使用它。

关于rust - Rust 中带有私有(private)类型的显式类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72151004/

相关文章:

rust - 如何在 Rust 中进行高阶组合?

python - Selenium Chromedriver Python - 使用 Tor 代理加载 ModHeader 扩展时为 'failed to wait for extension background page to load'

ios - 使用 linux 为 IOS 编译 TOR

Android:在端口 9150 连接到 Tor SOCKS 代理抛出 `SocketException` ;仅当我安装 Tor Android 应用程序时才有效

swift - 如何将Character类型注解转成String类型注解?

rust - 命名包含字符串 ".rs"的 crate 有问题吗?

c - Rust 中使用 C FFI 的代码如何与 header 保持同步?

struct - 结构间共享的方法

java - 如何从 Java 8 中的 getAnnotatedParameterTypes() 获取泛型类型信息?