#rust
Как реализовать TraitFoo для структуры Foo?
#[derive(Debug)]
struct Foo<'f>{
os: Option<&'f str>
}
impl<'f> Foo<'f> {
fn new(x:&'f str) -> Foo<'f>{
Foo{
os:Some(x)
}
}
}
trait TraitFoo {
fn foo(x:&str) -> Self;
}
impl<'f> TraitFoo for Foo<'f>{
fn foo(x:&str) -> Foo<'f> {
Foo{
os:Some(x)
}
}
}
fn main() {
println!("{:?}", Foo::new("one"));
println!("{:?}", Foo::foo("two"));
}
Этот код компилится с ошибкой:
G:\Work\Rust\test01\src\lf_trait.rs:21:12: 21:13 error: cannot infer an appropriate
lifetime for automatic coercion due to conflicting requirements
G:\Work\Rust\test01\src\lf_trait.rs:21 os:Some(x)
^
G:\Work\Rust\test01\src\lf_trait.rs:19:2: 23:3 help: consider using an explicit lifetime
parameter as shown: fn foo(x: &'f str) -> Foo<'f>
G:\Work\Rust\test01\src\lf_trait.rs:19 fn foo(x:&str) -> Foo<'f> {
G:\Work\Rust\test01\src\lf_trait.rs:20 Foo{
G:\Work\Rust\test01\src\lf_trait.rs:21 os:Some(x)
G:\Work\Rust\test01\src\lf_trait.rs:22 }
G:\Work\Rust\test01\src\lf_trait.rs:23 }
Если добавить 'f в функции foo() то получим другую ошибку:
G:\Work\Rust\test01\src\lf_trait.rs:19:2: 23:3 error: method `foo` has an incompatible
type for trait: expected bound lifetime parameter , found concrete lifetime [E0053]
G:\Work\Rust\test01\src\lf_trait.rs:19 fn foo(x:&'f str) -> Foo<'f> {
G:\Work\Rust\test01\src\lf_trait.rs:20 Foo{
G:\Work\Rust\test01\src\lf_trait.rs:21 os:Some(x)
G:\Work\Rust\test01\src\lf_trait.rs:22 }
G:\Work\Rust\test01\src\lf_trait.rs:23 }
Перепробовал еще кучу вариантов. Объясните как это правильно сделать.
Ответы
Ответ 1
Вот ответ с английского форума от llogiq: Нужно указать время жизни в определении трэйта trait TraitFoo<'a> { fn foo(x: &'a str) -> Self; } impl<'a> TraitFoo<'a> for Foo<'a> { fn foo(x:&'a str) -> Foo<'a> { Foo{ os:Some(x) } } }
Комментариев нет:
Отправить комментарий