Replies: 4 comments 6 replies
-
You can't assign values when you declare fields, you must initialize them in the constructor init. |
Beta Was this translation helpful? Give feedback.
-
thanks but just to clarify, my question is whether it's possible to allow default values when declaring fields for structs w a value constructor given the point of the constructor is to cut down on the boilerplate for getting full value semantics. if we can't do default values when initialising here, it really limits the use of the value constructor |
Beta Was this translation helpful? Give feedback.
-
You could use rust's trick with a trait Default:
@staticmethod
fn default() -> Self: ...
@value
struct MyPet(Default):
var name: String
var age: Int
@staticmethod
fn default() -> Self:
return MyPet("", 7)
fn main():
var pet = MyPet.default() Since Not sure if mojo will eventually allow default values in |
Beta Was this translation helpful? Give feedback.
-
honestly though, you're better off just implementing your own @value
struct MyPet:
var name: String
var age: Int
fn __init__(inout self, name: String):
self.name = name
self.age = 7 The Ideally, mojo will eventually give us decorator hooks for structs so we could do more metaprogramming on a struct in a pre-compile phase (so you could use something like python's |
Beta Was this translation helpful? Give feedback.
-
Is there a way to use the value decorator and have default arguments in a struct? As per below, I'm getting an error at the initialisation as well as when calling the struct.
Beta Was this translation helpful? Give feedback.
All reactions