Skip to content

Commit

Permalink
[External] [stdlib] Add Defaultable trait (#39797)
Browse files Browse the repository at this point in the history
[External] [stdlib] Add `Defaultable` trait

Add a `Defaultable` trait for describing a type which has a constructor
with no arguments.

Co-authored-by: Helehex <[email protected]>
Closes modularml#2526
MODULAR_ORIG_COMMIT_REV_ID: aed69a25ecf531873f944466a1cb5d7652dd7425

Signed-off-by: Lukas Hermann <[email protected]>
  • Loading branch information
helehex authored and lsh committed May 17, 2024
1 parent f974e61 commit 0fb9e50
Showing 1 changed file with 34 additions and 0 deletions.
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):
"""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

0 comments on commit 0fb9e50

Please sign in to comment.