artemiogr97
artemiogr97
MModular
Created by artemiogr97 on 4/14/2024 in #questions
Optional string argument
Is there a simple way to create a function that takes an optional String argument with no default value (assigned to None) ? I tried the following:
fn my_func(my_string: Optional[String] = None)-> String:
...
fn my_func(my_string: Optional[String] = None)-> String:
...
this works for a String but calling the function with a StringLiteral does not: my_func("my_string") gives the following error invalid call to 'my_func': argument #0 cannot be converted from 'StringLiteral' to 'Optional[String]' I guess one way to make it work for now is to use a default value as follows:
fn my_func(my_string: String = "my_default_string")-> String:
...
fn my_func(my_string: String = "my_default_string")-> String:
...
But this does not allow to distinguish between a bad input and an empty imput
17 replies
MModular
Created by artemiogr97 on 4/4/2024 in #questions
Lifecycle doc clarification
I was reading https://docs.modular.com/mojo/manual/lifecycle/life#move-constructor, the following struc is given as an example:
struct HeapArray:
var data: Pointer[Int]
var size: Int

fn __init__(inout self, size: Int, val: Int):
self.size = size
self.data = Pointer[Int].alloc(self.size)
for i in range(self.size):
self.data.store(i, val)

fn __copyinit__(inout self, existing: Self):
# Deep-copy the existing value
self.size = existing.size
self.data = Pointer[Int].alloc(self.size)
for i in range(self.size):
self.data.store(i, existing.data.load(i))

fn __moveinit__(inout self, owned existing: Self):
print("move")
# Shallow copy the existing value
self.size = existing.size
self.data = existing.data
# Then the lifetime of "existing" ends here, but
# Mojo does NOT call its destructor

fn __del__(owned self):
self.data.free()
struct HeapArray:
var data: Pointer[Int]
var size: Int

fn __init__(inout self, size: Int, val: Int):
self.size = size
self.data = Pointer[Int].alloc(self.size)
for i in range(self.size):
self.data.store(i, val)

fn __copyinit__(inout self, existing: Self):
# Deep-copy the existing value
self.size = existing.size
self.data = Pointer[Int].alloc(self.size)
for i in range(self.size):
self.data.store(i, existing.data.load(i))

fn __moveinit__(inout self, owned existing: Self):
print("move")
# Shallow copy the existing value
self.size = existing.size
self.data = existing.data
# Then the lifetime of "existing" ends here, but
# Mojo does NOT call its destructor

fn __del__(owned self):
self.data.free()
what does Then the lifetime of "existing" ends here, but Mojo does NOT call its destructor mean? I understand that existing.data must not be free but what about existing.size? is it freed even though the destructor is not called? in theory a copy was made by doing self.size = existing.size
5 replies