Is it possible to define a module in the same motoko file of an actor?

Is it possible to define a module in the same motoko file of an actor?

module {
    public type mytype ...
    public func myfunc ...
};

actor {
}

If possible, how can I call mytype and myfunc from inside the actor code?

By naming the module like this:

module M {
    public type mytype ...

To answer the first question, I expected to get a rejection like “the actor must be the only definition in a top-level source file”, but got

$ moc -c forum.mo 
forum.mo:6.1-7.2: type error [M0038], misplaced await
forum.mo:6.1-7.2: type error [M0037], misplaced async expression; try enclosing in an async function

This is probably a bug and related to the somewhat convoluted way how actors are treated internally in the compiler. If you get the same error, you could raise an issue about this.

PS: this is my current source:

module M {
    public type mytype = Int;
    public func myfunc() : mytype = 42;
};

actor A {
}
1 Like

The interpreter allows this, but when compiling to wasm, the only thing allowed in the main actor file is a sequence of imports followed by the actor itself.

The solution is to move the module into its own file and import it into the actor.

1 Like