Skip to content

Instantly share code, notes, and snippets.

@yihuang
Last active July 26, 2019 14:45
Show Gist options
  • Select an option

  • Save yihuang/df12f84c85eba48efed55acc896a2cbc to your computer and use it in GitHub Desktop.

Select an option

Save yihuang/df12f84c85eba48efed55acc896a2cbc to your computer and use it in GitHub Desktop.
cyclic type reference in rust
use std::fmt;
trait Listener where Self: Sized + fmt::Debug {
fn on_event(&self, obj: &TestObject<Self>, args: &str);
}
#[derive(Debug)]
struct TestObject<F> where F:Listener {
listener: F
}
#[derive(Debug)]
struct TestListener;
impl Listener for TestListener {
fn on_event(&self, obj: &TestObject<Self>, args: &str) {
println!("on_event {:?} {}", obj, args);
}
}
fn main() {
let listener = TestListener{};
let obj = TestObject{listener: listener};
obj.listener.on_event(&obj, "hello world");
}
@yihuang
Copy link
Author

yihuang commented Jul 26, 2019

error[E0277]: the size for values of type `Self` cannot be known at compilation time
 --> test.rs:2:5
  |
2 |     fn on_event(obj: &TestObject<Self>, args: &str);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `Self`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = help: consider adding a `where Self: std::marker::Sized` bound
note: required by `TestObject`
 --> test.rs:5:1
  |
5 | struct TestObject<F> where F: Listener {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

@yihuang
Copy link
Author

yihuang commented Jul 26, 2019

The most recent version is fixed by using trait object.

@yihuang
Copy link
Author

yihuang commented Jul 26, 2019

Tried with trait object again, it also works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment