Skip to content

Instantly share code, notes, and snippets.

@modularbot
Created April 26, 2024 16:28
Show Gist options
  • Save modularbot/6aed759930420cd70f38795dbcb874fe to your computer and use it in GitHub Desktop.
Save modularbot/6aed759930420cd70f38795dbcb874fe to your computer and use it in GitHub Desktop.
struct DemoStruct(CollectionElement, Stringable):
var member1: List[Int]
fn __init__(inout self, member1: List[Int]) -> None:
self.member1 = member1
print("Called constructor for " + str(self))
fn __copyinit__(inout self, other: Self) -> None:
self.member1 = other.member1
print("Called copy constructor for " + str(self))
fn __moveinit__(inout self, owned other: Self) -> None:
self.member1 = other.member1
print("Called move constructor for " + str(self))
fn __del__(owned self) -> None:
print("Calling destructor for " + str(self))
fn __str__(self) -> String:
var return_value = String("DemoStruct(List(")
for index in range(len(self.member1) - 1):
return_value += str(self.member1[index]) + ", "
return_value += str(self.member1[-1]) + "))"
return return_value
fn main() -> None:
var demo_obj_1 = DemoStruct(List(1, 2, 3, 4, 5))
var demo_obj_2 = demo_obj_1
# Copy constructor is called here, even though no mutation occurs and Mojo is supposed to have copy-on-write/lazy copying semantics
print(demo_obj_1)
print(demo_obj_2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment