简体   繁体   English

特质约束T:从 <Result<T, Error> &gt;不满意

[英]Trait bound T: From<Result<T, Error>> is not satisfied

I want to load nonce from a toml config file. 我想从toml配置文件加载nonce nonce is retrieved in pub fn get_nonce() . noncepub fn get_nonce()检索。 I'd like to instantiate the result to salt of lazy_static macro type HarshBuilder . 我想将结果实例化为lazy_static宏类型HarshBuilder salt

use config::{Config, File, FileFormat, ConfigError};
use harsh::{Harsh, HarshBuilder};
use settings::Server;

const CFG_DEFAULT: &'static str = "conf/default";

lazy_static! {
    static ref MASK: Harsh = HarshBuilder::new()
        .length(7)
        .salt(get_nonce())
        .init()
        .expect("invalid harsh build");
}

fn conf_file() -> Config {
    let mut cfg = Config::default();
    cfg.merge(File::from_str(CFG_DEFAULT, FileFormat::Toml))
        .unwrap();

    cfg
}

pub fn get_nonce() -> Result<Vec<u8>, ConfigError> {
    let conf = conf_file();
    let search: Server = conf.get("server").unwrap();
    let nonce: Vec<u8> = search.nonce.into_bytes();

    Ok(nonce)
}

The compiler returns an error: 编译器返回错误:

error[E0277]: the trait bound `std::vec::Vec<u8>: std::convert::From<std::result::Result<std::vec::Vec<u8>, config::ConfigError>>` is not satisfied
--> lib.rs:40:14
|
40 |     .salt(get_nonce())
|         ^^^^ the trait 
|
`std::convert::From<std::result::Result<std::vec::Vec<u8>, config::ConfigError>>` is not implemented for `std::vec::Vec<u8>`

|
= help: the following implementations were found:
         <std::vec::Vec<u8> as std::convert::From<std::ffi::CString>>
         <std::vec::Vec<u8> as std::convert::From<std::string::String>>
         <std::vec::Vec<T> as std::convert::From<&'a mut [T]>>
         <std::vec::Vec<T> as std::convert::From<std::borrow::Cow<'a, [T]>>>
       and 5 others
= note: required because of the requirements on the impl of `std::convert::Into<std::vec::Vec<u8>>` for `std::result::Result<std::vec::Vec<u8>, config::ConfigError>`

So get_nonce() returns an enum result of Result<String, ConfigError> . 因此get_nonce()返回Result<String, ConfigError>的枚举结果。 This does not appear to satisfy salt Option<Vec<u8>> . 这似乎不满足salt Option<Vec<u8>> The attempt you see above is to convert Result enum to Vec<u8> . 您在上面看到的尝试是将Result枚举转换为Vec<u8> However, this does not fix the error. 但是,这不能解决错误。

Here is the HarshBuilder trait implementation for review: 这是HarshBuilder特质实现供审查:

/// Note that this factory will be consumed upon initialization.
#[derive(Debug, Default)]
pub struct HarshBuilder {
    salt: Option<Vec<u8>>,
    // ...ommitted for brevity
}

impl HarshBuilder {
/// Creates a new `HarshBuilder` instance.
pub fn new() -> HarshBuilder {
    HarshBuilder {
        salt: None,
        // ...ommited for brevity
    }
}

/// Note that this salt will be converted into a `[u8]` before use, meaning
/// that multi-byte utf8 character values should be avoided.
pub fn salt<T: Into<Vec<u8>>>(mut self, salt: T) -> HarshBuilder {
    self.salt = Some(salt.into());
    self
}

Trait bounds and lifetime elision is still a subject that I'm trying to wrap my head around. 特质界限和终生淘汰仍然是我要努力解决的问题。 I can really use some guidance. 我真的可以使用一些指导。 Perhaps, this may be the reason as to why the answer is not completely obvious for me here. 也许,这可能就是为什么答案对我来说并不完全明显的原因。

Since your get_nonce function returns a Result , you need to handle the possible error. 由于您的get_nonce函数返回Result ,因此您需要处理可能的错误。 There are three ways you can fix your code here: 您可以通过三种方式在此处修复代码:

  • Given that get_nonce never returns an error, you can simply change it so that it returns nonce directly instead of Ok(nonce) . 鉴于get_nonce永远不会返回错误,您可以简单地对其进行更改,以使其直接返回nonce而不是Ok(nonce)
  • Or you can call unwrap on the result to access the Vec<u8> that's inside (and crash if you later change get_nonce to generate errors). 或者,您可以对结果调用unwrap ,以访问其中的Vec<u8> (如果以后更改get_nonce来生成错误, get_nonce崩溃)。
  • Or you can add proper error handling all around (get rid of the unwrap s and use try! or the ? operator to propagate errors and catch them properly at some top-level point). 或者,您可以添加适当的错误处理方法(摆脱unwrap并使用try!?运算符传播错误并在某个顶级点正确捕获它们)。

The Option<Vec<u8>> is a red herring, the important thing is the prototype of salt() , and as you can see in the definition of salt : Option<Vec<u8>>是一个红色鲱鱼,重要的是salt()的原型,正如您在salt的定义中所看到的:

pub fn salt<T: Into<Vec<u8>>>(mut self, salt: T)

it expects an argument that satisfies the trait Into<Vec<u8>> . 它期望一个满足特征Into<Vec<u8>> From the documentation you can see that there are these generic implementations of Into<T> : 文档中,您可以看到Into<T>这些通用实现:

  • From<T> for U implies Into<U> for T From<T>U意味着Into<U>T
  • Into is reflexive, which means that Into<T> for T is implemented. Into是自反的,这意味着已实现T Into<T>

So you may pass to salt either: 因此,您可以通过以下任一方法来salt

  • A value of type Vec<u8> . Vec<u8>类型的值。
  • A value of type T if there is such From<T> is implemented for Vec<u8> . 如果Vec<u8>实现了这样的From<T>则类型为T的值。
  • A value that implements Into<Vec<u8>> directly. 直接实现Into<Vec<u8>>

Now, you have a value of type Result<Vec<u8>, ConfigError> , that satisfies none of the above. 现在,您有一个类型Result<Vec<u8>, ConfigError> ,不能满足上述任何一个条件。 And that is what all those error messages are trying to tell you. 这就是所有这些错误消息都试图告诉您的。

The easy solution is to change your function into: 简单的解决方案是将您的功能更改为:

pub fn get_nonce() -> Vec<u8> {
     ....
     nonce
}

If you cannot change that return type you can use unwrap() to get the real value from a Result() (and crash on error): 如果您无法更改该返回类型,则可以使用unwrap()Result()获取实际值(并在发生错误时崩溃):

    .length(7)
    .salt(get_nonce().unwrap())
    .init()

If the get_nonce() function can really fail, then you would have to manage the error properly, maybe making your MASK value of type Result<Harsh, ConfigError> ? 如果get_nonce()函数确实可能失败,那么您将不得不正确管理该错误,也许使您的MASK值为Result<Harsh, ConfigError>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不满足特征绑定`T:std :: fmt :: Display` - The trait bound `T: std::fmt::Display` is not satisfied 特质绑定`futures :: Future <Item=Arc<T> ,错误=框 <Error + Send> &gt;:发送不满意 - The trait bound `futures::Future<Item=Arc<T>, Error=Box<Error + Send>>: Send` is not satisfied Rust中不满足特征限制 - The trait bound is not satisfied in Rust 特质界限不满足 - The trait bound is not satisfied 特征绑定不满足从元组特征构建 ndarray - Trait bound not satisfied building an ndarray from a tuple trait 错误[E0277]:特征绑定`std::result::Result&lt;_, Box<archivebzip2error> &gt;: std::error::Error` 不满足</archivebzip2error> - error[E0277]: the trait bound `std::result::Result<_, Box<ArchiveBzip2Error>>: std::error::Error` is not satisfied 我得到了特征绑定`T:sns_pub::_IMPL_DESERIALIZE_FOR_Message::_serde::Serialize`不满意 - I am getting the trait bound `T: sns_pub::_IMPL_DESERIALIZE_FOR_Message::_serde::Serialize` is not satisfied 为什么我的Result类型别名不满足failure :: Fail特质的约束? - Why is the failure::Fail trait bound not satisfied by my Result type alias? Result&lt;(), Box&lt;(dyn SomeTrait + &#39;static)&gt;&gt; 不满足 Trait Bound - Trait Bound is not satisfied for Result<(), Box<(dyn SomeTrait + 'static)>> 为什么? 运算符报错误“特征绑定NoneError:错误不满足”? - Why does the ? operator report the error "the trait bound NoneError: Error is not satisfied"?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM