您可以将 tokio_postgres::config::Config 转换为连接字符串吗?

Can you convert tokio_postgres::config::Config to connection string?

我想用 tokio_postgres crate. I created a Config object with a connection configuration. However, connect 函数建立数据库连接,该函数将连接字符串 (&str) 作为参数。在文档中我找不到任何方法将其转换为 (str)。手动构建连接字符串是唯一的选择吗?

我也试过使用Display trait

let mut db_config = Config::new();
db_config.
    host("localhost").
    user("admin").
    port(5432).
    password("secret_password").
    dbname("admin");

let (client, connection) =
    tokio_postgres::connect(format!("{}", db_config), NoTls).await.unwrap();

但没有成功

tokio_postgres::connect(format!("{}", db_config), NoTls).await.unwrap()                                            
                                      ^^^^^^^^^ `Config` cannot be formatted with the default formatter
   
= help: the trait `std::fmt::Display` is not implemented for `Config`

正在查看 the source code for tokio_postgres::connect, you can see that it first parses its &str argument into a Config, then calls Config::connect 结果。由于你已经有了一个Config,你可以直接调用它的connect方法:

let (client, connection) = Config::new()
    .host("localhost")
    .user("admin")
    .port(5432)
    .password("secret_password")
    .dbname("admin")
    .connect(NoTls)
    .await
    .unwrap();