相关疑难解决方法(0)

FromStr 和 TryFrom<String> 特征之间有什么区别?

当使用 Rust 中的 Serde 箱时,我尝试将#[serde(try_from = String)] 容器属性添加到实现的类型中FromStr,从而可以从字符串中解析。不幸的是,这对于 Serde 来说似乎还不够,从编译器错误消息来看,很明显我TryFrom<String>也必须手动实现。

为什么TryFrom<String>不为所有实现的类型自动实现FromStr?为什么字符串的错误转换有一个单独的特征?这两个特征有什么区别?

string type-conversion rust

8
推荐指数
1
解决办法
3645
查看次数

如何实现具有生命周期的FromStr?

我想为FromStr具有生命周期参数的结构实现:

use std::str::FromStr;

struct Foo<'a> {
    bar: &'a str,
}

impl<'a> FromStr for Foo<'a> {
    type Err = ();
    fn from_str(s: &str) -> Result<Foo<'a>, ()> {

        Ok(Foo { bar: s })
    }
}

pub fn main() {
    let foo: Foo = "foobar".parse().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

但是,编译器抱怨:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:11:12
   |
11 |         Ok(Foo { bar: s })
   |            ^^^
   |
help: consider using an explicit lifetime parameter as shown: fn from_str(s: …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
990
查看次数

标签 统计

rust ×2

string ×1

type-conversion ×1