简体   繁体   中英

Recursive call of interface implementation in rust language

How do I call recursively an interface I am implementing from the implementation of this interface?

I am doing the following thing:

import io::*;
import to_str::*;
enum some_enum {
  foo(~[some_enum]),
  bar
}

impl to_str for some_enum {
  fn to_str() -> str {
    alt self {
      bar { "bar" }
      foo(nest) { "foo" + nest.to_str() } // this line
    }
  }
}

fn main() {
  println(foo(~[bar,bar,bar]).to_str());
}

And it fails at compile time with

user@note ~/soft/mine/rust $ rustc example.rs && ./example 
example.rs:13:32: 13:43 error: failed to find an implementation of interface core::to_str::to_str for some_enum
example.rs:13             foo(nest) { "foo" + nest.to_str() }
                                              ^~~~~~~~~~~

Of course I can do an FP-like thing:

  foo(nest) { "foo" + nest.map(|x| { x.to_str() }).to_str() }

But why isn't the former case valid?

Seems like it can be solved with using impl of instead of impl .

impl without of acts like interface-less implementation, with no actual interface involved.

(confirming to http://dl.rust-lang.org/doc/tutorial.html#interface-less-implementations )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM