我想找出 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>
哪里Self
是 arti_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/