[英]How do I implement FromStr with a concrete lifetime?
我想為具有生命周期參數的結構實現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 更改為
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
。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.