Skip to main content
Log in

Mojo trait

Defaultable

The Defaultable trait describes a type with a default constructor.

Implementing the Defaultable trait requires the type to define an __init__ method with no arguments:

struct Foo(Defaultable):
var s: String

fn __init__(inout self):
self.s = "default"
struct Foo(Defaultable):
var s: String

fn __init__(inout self):
self.s = "default"

You can now construct a generic Defaultable type:

fn default_init[T: Defaultable]() -> T:
return T()

var foo = default_init[Foo]()
print(foo.s)
fn default_init[T: Defaultable]() -> T:
return T()

var foo = default_init[Foo]()
print(foo.s)
default
default

Implemented traits

AnyType

Methods

__init__

__init__(inout self: T, /)

Create a default instance of the value.

Was this page helpful?