本文介绍了如何实现具有具体生命周期的 FromStr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为带有生命周期参数的结构体实现 FromStr
:
I want to implement FromStr
for a struct with a lifetime parameter:
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();
}
然而,编译器抱怨:
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: &'a str) -> Result<Foo<'a>, ()>
--> src/main.rs:9:5
|
9 | fn from_str(s: &str) -> Result<Foo<'a>, ()> {
| ^
将实现更改为
impl<'a> FromStr for Foo<'a> {
type Err = ();
fn from_str(s: &'a str) -> Result<Foo<'a>, ()> {
Ok(Foo { bar: s })
}
}
给出这个错误
error[E0308]: method not compatible with trait
--> src/main.rs:9:5
|
9 | fn from_str(s: &'a str) -> Result<Foo<'a>, ()> {
| ^ lifetime mismatch
|
= note: expected type `fn(&str) -> std::result::Result<Foo<'a>, ()>`
= note: found type `fn(&'a str) -> std::result::Result<Foo<'a>, ()>`
note: the anonymous lifetime #1 defined on the block at 9:51...
--> src/main.rs:9:52
|
9 | fn from_str(s: &'a str) -> Result<Foo<'a>, ()> {
| ^
note: ...does not necessarily outlive the lifetime 'a as defined on the block at 9:51
--> src/main.rs:9:52
|
9 | fn from_str(s: &'a str) -> Result<Foo<'a>, ()> {
| ^
help: consider using an explicit lifetime parameter as shown: fn from_str(s: &'a str) -> Result<Foo<'a>, ()>
--> src/main.rs:9:5
|
9 | fn from_str(s: &'a str) -> Result<Foo<'a>, ()> {
| ^
推荐答案
我不相信你可以在这种情况下实现 FromStr
.
I don't believe that you can implement FromStr
in this case.
fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err>;
特征定义中没有将输入的生命周期与输出的生命周期联系起来.
There's nothing in the trait definition that ties the lifetime of the input to the lifetime of the output.
不是直接的答案,但我只是建议制作一个接受引用的构造函数:
Not a direct answer, but I'd just suggest making a constructor that accepts the reference:
struct Foo<'a> {
bar: &'a str
}
impl<'a> Foo<'a> {
fn new(s: &str) -> Foo {
Foo { bar: s }
}
}
pub fn main() {
let foo = Foo::new("foobar");
}
这样做的附带好处是没有任何故障模式 - 无需解包
.
This has the side benefit of there not being any failure modes - no need to unwrap
.
你也可以只实现From
:
struct Foo<'a> {
bar: &'a str,
}
impl<'a> From<&'a str> for Foo<'a> {
fn from(s: &'a str) -> Foo<'a> {
Foo { bar: s }
}
}
pub fn main() {
let foo: Foo = "foobar".into();
}
这篇关于如何实现具有具体生命周期的 FromStr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!