実現したいこと
構造体内部に保持した Vector<str> へ要素を追加するためのメソッドを作成したいです。
ライフタイムに関するエラーを解消する方法と、考え方をご教示いただきたく、よろしくお願いいたします。
- Memo というクラスを作成しました
- インスタンス変数に lines として 文字列の配列を定義しました(実装は Vector )
- lines に文字列を追加するための add メソッドを定義しました
発生しているエラーメッセージ
error[E0261]: use of undeclared lifetime name `'a` --> src/main.rs:15:11 | 15 | impl Memo<'a> { | - ^^ undeclared lifetime | | | help: consider introducing lifetime `'a` here: `<'a>`
該当のソースコード
rust
1fn main() { 2 let mut text = Memo::new(); 3 text.add("name, category") 4 .add("Apple, Fruit") 5 .add("Beef, Meet") 6 .add("Banana, Fruit"); 7 8 println!("{:?}", text.data); 9} 10 11struct Memo<'a> { 12 data: Vec<&'a str>, 13} 14 15impl Memo<'a> { 16 fn new() -> Memo<'static> { 17 Memo { 18 data: vec![], 19 } 20 } 21 22 fn add<'a>(&mut self, line: &'a str) -> &mut Memo { 23 self.data.push(line); 24 self 25 } 26}
Cargo.toml
[package] name = "docfood" version = "0.1.0" edition = "2021"
試したこととエラーメッセージ
impl Memo
からライフタイムの指定を除外してみました。
error[E0726]: implicit elided lifetime not allowed here --> src/main.rs:15:6 | 15 | impl Memo { | ^^^^- help: indicate the anonymous lifetime: `<'_>` | = note: assuming a `'static` lifetime...
impl Memo<'_>
としてみました。
error[E0312]: lifetime of reference outlives lifetime of borrowed content... --> src/main.rs:23:25 | 23 | self.lines.push(line); | ^^^^ | note: ...the reference is valid for the lifetime `'_` as defined here... --> src/main.rs:15:11 | 15 | impl Memo<'_> { | ^^ note: ...but the borrowed content is only valid for the lifetime `'a` as defined here --> src/main.rs:22:12 | 22 | fn add<'a>(&mut self, line: &'a str) -> &mut Memo { | ^^
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/07 09:33