我正在尝试执行板条mysql箱文档的基本示例的开头,但使用格式化字符串而不是完全硬编码的字符串:
use mysql::*;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
// These will be read from a config file
let user = "root";
let pw = "password";
let host = "localhost";
let port = 3307;
let db = "db_name";
let url = format!("mysql://{user}:{pw}@{host}:{port}/{db}");
let pool = Pool::new(url)?; // Error at this line
let mut conn = pool.get_conn()?;
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
但是我收到这个错误:
error[E0277]: the trait bound `Opts: From<std::string::String>` is not satisfied
--> src/main.rs:13:23
|
13 | let pool = Pool::new(url)?;
| --------- ^^^ the trait `From<std::string::String>` is not implemented for `Opts`
| |
| required by a bound introduced by this call
Run Code Online (Sandbox Code Playgroud)
我是 Rust 新手,整个晚上都在寻找解决方案。format!为什么没有执行的输出From<String>?如何传递格式化字符串Pool::new而不是硬编码字符串?谢谢
我会构建一个OptsBuilder而不是连接字符串:
use mysql::*;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
// These will be read from a config file
let user = "root";
let pw = "password";
let host = "localhost";
let port = 3307;
let db = "db_name";
let opts = OptsBuilder::new()
.user(Some(user))
.pass(Some(pw))
.ip_or_hostname(Some(host))
.tcp_port(port)
.db_name(Some(db));
let pool = Pool::new(opts)?;
let mut conn = pool.get_conn()?;
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
但如果你真的想要,你可以将生成String的转换format!为 a &str,因为涉及泛型,最简单的方法是使用.as_str():
let url = format!("mysql://{user}:{pw}@{host}:{port}/{db}");
let pool = Pool::new(url.as_str())?;
Run Code Online (Sandbox Code Playgroud)