gpt4 book ai didi

rust - 用特征别名替换特征绑定(bind)说 "the size for values cannot be known at compilation time"

转载 作者:行者123 更新时间:2023-12-03 11:43:38 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Sized is not implemented for the type Fn

(1 个回答)


2年前关闭。




在阅读了 trait aliases 之后,我试图切换这段代码:

pub fn authorize<LoadClient>(get_client: LoadClient) -> Result<String, ()> 
where
LoadClient: FnOnce(String) -> Result<Client, LoadingError>,
{
unimplemented!()
}


#![feature(trait_alias)]

trait LoadClient = FnOnce(String) -> Result<Client, ClientLoadingError>;

pub fn authorize(get_client: LoadClient) -> Result<String, ()> {
unimplemented!()
}

这给了我一个错误:

warning: trait objects without an explicit `dyn` are deprecated
--> src/oauth2/mod.rs:396:21
|
396 | get_client: LoadClient,
| ^^^^^^^^^^ help: use `dyn`: `dyn LoadClient`
|
= note: `#[warn(bare_trait_objects)]` on by default

error[E0277]: the size for values of type `(dyn std::ops::FnOnce(std::string::String) -> std::result::Result<oauth2::Client, oauth2::ClientLoadingError> + 'static)` cannot be known at compilation time
--> src/oauth2/mod.rs:396:9
|
396 | get_client: LoadClient,
| ^^^^^^^^^^ doesn't have a size known at compile-time
|

是否可以以这种方式使用特征别名?此函数在其他地方使用,因此最好有一个共享定义,而不是在每个使用它的地方重新定义它。

这与 Can match on Result here be replaced with map_err and "?" 有关

最佳答案

您仍然需要将其用作通用参数:

#![feature(trait_alias)]

pub trait LoadClient = FnOnce(String) -> Result<Client, ClientLoadingError>;

pub fn authorize<T>(get_client: T) -> Result<String, ()>
where
T: LoadClient,
{
unimplemented!()
}

您还需要公开 trait 别名,因为它是公共(public)接口(interface)的一部分。

关于rust - 用特征别名替换特征绑定(bind)说 "the size for values cannot be known at compilation time",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59720444/

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