Skip to content

rust (question?): cannot implement static method that returns result<> of resource #1571

@xnuk

Description

@xnuk
// wit/choco.wit

package xnuk:choco;

interface runner {
	resource state {
		from-string: static func(source: string) -> result<state, string>;
		is-choco: func() -> bool;
	}
}

world choco {
	export runner;
}
// src/lib.rs

use crate::exports::xnuk::choco::runner;

wit_bindgen::generate!("choco");

struct Component;
impl runner::Guest for Component {
	type State = MyState;
}

struct MyState {
	is_choco: bool,
}
impl runner::GuestState for MyState {
	fn from_string(source: String) -> Result<MyState, String> {
	//                                ^^^^^^^^^^^^^^^^^^^^^^^ expected `State`, found `MyState`
		if source.is_empty() {
			return Err("string is empty".to_string());
		}

		Ok(MyState {
			is_choco: source.to_ascii_lowercase() == "choco",
		})
	}
	fn is_choco(&self) -> bool {
		self.is_choco
	}
}
   Compiling mini-wit v0.1.0 (/home/xnuk/mini-wit)
error[E0053]: method `from_string` has an incompatible type for trait
  --> src/lib.rs:14:36
   |
14 |     fn from_string(source: String) -> Result<MyState, String> {
   |                                       ^^^^^^^^^^^^^^^^^^^^^^^ expected `State`, found `MyState`
   |
note: type in trait
  --> src/lib.rs:3:1
   |
 3 | wit_bindgen::generate!("choco");
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: expected signature `fn(String) -> Result<State, _>`
              found signature `fn(String) -> Result<MyState, _>`
   = note: this error originates in the macro `wit_bindgen::generate` (in Nightly builds, run with -Z macro-backtrace for more info)
help: change the output type to match the trait
   |
14 -     fn from_string(source: String) -> Result<MyState, String> {
14 +     fn from_string(source: String) -> Result<State, String> {
   |

For more information about this error, try `rustc --explain E0053`.
error: could not compile `mini-wit` (lib) due to 1 previous error

I want to check some logic before creating resources, and reject to create it if logic doesn't match. But wit-bindgen requires Result<runner::State, _> to return, not Result<Self, _>, so it seems impossible to do this. I'm new to the WIT-things, so am I doing wrong? Is there a workaround for this?

Maybe related?: #1114

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions