gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:50:01 25 4
gpt4 key购买 nike

我想为一个带有生命周期参数的结构实现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();
}

但是,编译器会报错:

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>, ()> {
| ^

Playpen

最佳答案

我不认为您可以在这种情况下实现 FromStr

fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err>;

特征定义中没有任何内容将输入的生命周期与输出的生命周期联系起来。

不是直接的答案,但我只是建议制作一个接受引用的构造函数:

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");
}

这有一个附带的好处,即没有任何故障模式 - 无需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();
}

关于rust - 如何实现具有具体生命周期的 FromStr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28931515/

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