gpt4 book ai didi

rust - 为什么不能将 Box 传递给以 &mut Trait 作为参数的函数

转载 作者:行者123 更新时间:2023-12-02 01:38:45 46 4
gpt4 key购买 nike

我确定之前有人问过这个问题,但还没有遇到能准确描述此处情况的问题。我有以下代码:

let mut pool: Box<dyn redis::aio::ConnectionLike> = <...>
redis::cmd(COMMAND)
.arg(LIST)
.arg(value)
.query_async(&mut pool)
.await
.unwrap();

这会返回错误:

error[E0277]: the trait bound `std::boxed::Box<dyn redis::aio::ConnectionLike>: redis::aio::ConnectionLike` is not satisfied
--> svix-server/src/queue/redis.rs:66:30
|
66 | .query_async(&mut pool)
| ----------- ^^^^^^^^^ the trait `redis::aio::ConnectionLike` is not implemented for `std::boxed::Box<dyn redis::aio::ConnectionLike>`
| |
| required by a bound introduced by this call
|

问题 1 -- 为什么错误提示未为 Box<dyn redis::aio::ConnectionLike> 实现特征?它不应该至少说&Box...吗? ?

无论如何,如果我改为尝试通过 pool.as_mut()query_async ,我得到这个错误:

error[E0277]: the size for values of type `dyn redis::aio::ConnectionLike` cannot be known at compilation time
--> svix-server/src/queue/redis.rs:66:30
|
66 | .query_async(pool.as_mut())
| ----------- ^^^^^^^^^^^^^ doesn't have a size known at compile-time
| |
| required by a bound introduced by this call
|
= help: the trait `Sized` is not implemented for `dyn redis::aio::ConnectionLike`

问题 2 -- 为什么是 Sized这里需要吗? Rust 中的引用不总是 Sized

问题 3 -- 有什么方法可以传递 dyn ConnectionLike对此

query_async方法,引用如下:

#[inline]
#[cfg(feature = "aio")]
pub async fn query_async<C, T: FromRedisValue>(&self, con: &mut C) -> RedisResult<T>
where
C: crate::aio::ConnectionLike,
{
...
}

最佳答案

Question 1 -- Why does the error say the trait is not implemented for Box<dyn redis::aio::ConnectionLike>? Shouldn't it at least say &Box...?

不,因为引用不是泛型的一部分 C . Rust 不会命名整个 类型,它只会命名两个类型中不匹配的部分。该函数接受 &mut CC是匹配的通用部分。 Box type 是 C 的替代品,并且它没有实现这个特性。

Question 2 -- Why is Sized required here? Isn't a reference in Rust always Sized?

引用确实是Sized ,但如上所述,我们正在匹配类型 &mut dyn redis::aio::ConnectionLike反对&mut C .这导致 C正在dyn redis::aio::ConnectionLike .

在 Rust 中,泛型类型有 Sized默认绑定(bind) 您必须明确指定 ?Sized一定要放宽这个,这个功能的作者没有做到。因此,C必须实现 Sized , 和 dyn redis::aio::ConnectionLike没有。

Question 3 -- Is there any way to to pass a dyn ConnectionLike to this

可能,但不是直接的。您将需要实现一个类型来包装对 dyn ConnectionLike 的引用。或 Box<dyn ConnectionLike>并通过它。像这样的东西:

struct BoxedConnectionLike(Box<dyn ConnectionLike>);

impl ConnectionLike for BoxedConnectionLike {
// Implement proxy functions for the trait.
}

关于rust - 为什么不能将 Box<dyn Trait> 传递给以 &mut Trait 作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71933895/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com