Box<dyn ConnectionLike> 调用 hset 报 E0599 如何解决
数据小陈
结论
hset 来自 redis::Commands,不是 ConnectionLike 的成员。dyn ConnectionLike 是未定长类型,不满足 Commands 要求的 Sized 约束;Box<dyn ConnectionLike> 也没有自动实现 ConnectionLike。因此,编译器无法在这个 trait object 上调用 hset。另外,发送命令需要可变借用连接,所以 set_name 应使用 &mut self。
原因
Commands 的 blanket impl 大致要求 Self: ConnectionLike + Sized,而 hset 这类泛型方法本身也不是 object-safe 的,不能直接在 dyn ConnectionLike 上调用。错误里的两条 note 分别对应:
Box<dyn ConnectionLike>: ConnectionLike不成立;dyn ConnectionLike: Sized不成立。
方案一:保留 Box,改用 redis::cmd
如果确实要保留 trait object,可以直接发送底层命令。Cmd::query 接收 &mut dyn ConnectionLike:
use redis::{ConnectionLike, RedisError};
struct MyRedis {
connection: Box<dyn ConnectionLike>,
}
impl MyRedis {
pub fn set_name(&mut self, name: &str) -> Result<(), RedisError> {
let _: () = redis::cmd("HSET")
.arg("me")
.arg("name")
.arg(name)
.query(self.connection.as_mut())?;
Ok(())
}
}
调用时也要用可变变量:
let mut redis = MyRedis { connection };
redis.set_name("bla")?;
方案二:用泛型包装,继续使用 Commands
如果希望继续使用 hset 这类 Commands 方法,推荐把 MyRedis 写成泛型:
use redis::{Commands, RedisError};
struct MyRedis<C> {
connection: C,
}
impl<C: Commands> MyRedis<C> {
pub fn set_name(&mut self, name: &str) -> Result<(), RedisError> {
self.connection.hset("me", "name", name)?;
Ok(())
}
}
生产代码可以传 redis::Connection,测试时传实现了 ConnectionLike 的 mock 类型。这样能继续使用 Commands API,也能避免 trait object 的 Sized 问题。
方案三:用本地 newtype 包住 Box
如果必须使用 trait object,又不想写原始命令,可以定义本地 newtype 并实现 ConnectionLike,再由 blanket impl 获得 Commands。不同 redis 版本的 ConnectionLike 方法可能略有差异,按编译器提示补齐即可:
use redis::{Commands, ConnectionLike, RedisError, Value};
struct BoxedConnection(Box<dyn ConnectionLike>);
impl ConnectionLike for BoxedConnection {
fn req_packed_command(&mut self, cmd: &[u8]) -> redis::RedisResult<Value> {
self.0.req_packed_command(cmd)
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> redis::RedisResult<Vec<Value>> {
self.0.req_packed_commands(cmd, offset, count)
}
fn get_db(&self) -> i64 {
self.0.get_db()
}
}
struct MyRedis {
connection: BoxedConnection,
}
impl MyRedis {
pub fn set_name(&mut self, name: &str) -> Result<(), RedisError> {
self.connection.hset("me", "name", name)?;
Ok(())
}
}
注意事项
Commands的方法通常需要&mut self,不要把set_name写成&self。hset返回RedisResult,用?传播错误,不要直接赋值给()。- 测试用的 mock 需要实现
ConnectionLike,这样Commands的 blanket impl 才能覆盖它。 - 如果只需要少量命令,
redis::cmd(...).query(...)更直接;大量使用CommandsAPI 时,泛型或 newtype 更合适。
备注:内容仅供参考。
