E4213#
Compiler diagnostic name: invalid_constr_self_type.
Custom constructors cannot be defined for trait object types such as &Trait.
MoonBit supports custom constructors for user-defined concrete types, including
structs, enums, and newtypes. A trait object is an erased runtime view rather
than a concrete type that can own a constructor, so fn &Trait::Trait(...) is
rejected.
Erroneous example#
///|
pub(open) trait Renderable {
fn render(Self) -> String
}
///|
pub fn[X : Renderable] &Renderable::Renderable(value : X) -> &Renderable {
value as &Renderable
}
The erroneous example tries to make &Renderable::Renderable a constructor for
the trait object type.
Suggestion#
Use a normal function to convert a value to the trait object, or define a custom constructor on a concrete wrapper type.
///|
pub(open) trait Renderable {
fn render(Self) -> String
}
///|
pub fn[X : Renderable] as_renderable(value : X) -> &Renderable {
value as &Renderable
}