Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[stdlib] add Defaultable trait #2526

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 34 additions & 0 deletions stdlib/src/builtin/value.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,40 @@ trait Copyable:
...


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:

```mojo
struct Foo(Defaultable):
var s: String

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

You can now construct a generic `Defaultable` type:

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

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

```plaintext
default
```
"""

fn __init__(inout self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have the name default

"""Create a default instance of the value."""
...


trait CollectionElement(Copyable, Movable):
"""The CollectionElement trait denotes a trait composition
of the `Copyable` and `Movable` traits.
Expand Down