Rust での Iterator 返し + from_fn + Self
自分が作りたいもののためにメモ。きっと忘れて見返す。
こんな書き方できるんですねー。 ちょっと前までコンパイルエラーで落ちてた記憶がうっすらとあります。
#[derive(Debug)] struct SpanIdentity { trace_id: String, span_id: String, } #[derive(Debug)] struct SpanContext<'a> { id: SpanIdentity, parent_span: Option<&'a Self>, } impl<'a> SpanContext<'a> { fn context_iter(&'a self) -> impl Iterator<Item = &'a SpanContext<'a>> { let mut acc = self; std::iter::from_fn(move ||{ let r = acc.parent_span; acc = r.unwrap_or(acc); r }) } } fn main() { let a_a = SpanContext{id: SpanIdentity {trace_id: "a".to_owned(), span_id:"a".to_owned(),}, parent_span: None}; let a_b = SpanContext{id: SpanIdentity {trace_id: "a".to_owned(), span_id:"b".to_owned(),}, parent_span: Some(&a_a)}; let a_c = SpanContext{id: SpanIdentity {trace_id: "a".to_owned(), span_id:"c".to_owned(),}, parent_span: Some(&a_b)}; for x in a_c.context_iter() { println!("{:?}", x); } }