rust - Using a borrow as an associated trait type -
this code works:
struct test { val: string, } impl test { fn mut_out(&mut self) -> &string { self.val = string::from("something"); &self.val } }
however, more generic implementation not work:
struct test { val: string, } trait mutateout { type out; fn mut_out(&mut self) -> self::out; } impl mutateout test { type out = &string; fn mut_out(&mut self) -> self::out { self.val = string::from("something"); &self.val } }
the compiler cannot infer lifetime string borrow:
error[e0106]: missing lifetime specifier --> src/main.rs:13:16 | 11 | type out = &string; | ^ expected lifetime parameter
i cannot figure out way explicitly state lifetime of borrow, depends on function itself.
taking inspiration deref
trait, can remove reference associated type , instead note in trait want return reference associated type:
trait mutateout { type out; fn mut_out(&mut self) -> &self::out; } impl mutateout test { type out = string; fn mut_out(&mut self) -> &self::out { self.val = string::from("something"); &self.val } }
here it in playground. given function name mut_out
, if mutable reference after, here playground example well.
Comments
Post a Comment