I can’t hide it, I’ve been hit by Mojo FOMO! While I even have only myself guilty, I’m not going to be too hard on myself for that, for the reason that prospect of working with a latest programming language that is supposed to be a mix of my two favourite languages (C/C++ and Python) seems too good to be true!
Now there are a variety of posts that duplicate the examples within the Modular videos / Mojo docs (verbatim!), so as an alternative I’ve chosen my favourite starter function and object namely, the ever-present say_hello function and the HelloSayer class (struct).
In Python (3.8 and upwards) it could appear to be this:
%%python
def say_hello(to):
return f"Hello {to}!"o = say_hello('Gautam')
print(o)
>> Hello Gautam!
And now in Mojo, you can do it this manner:
def say_hello(to):
return 'Hello '+ to + '!'o = say_hello('Dev')
print(o)
>> Hello Dev!
Or, if you happen to actually need to be explicit and use strong type-checking by utilizing as an alternative of the dynamic :
from String import Stringfn say_hello(to: StringLiteral) -> String:
return String('Hello ') + to + String('!')
let o:String = say_hello('Kian')
print(o)
>> Hello Kian!
Mojo 🔥 uses structs for the object-oriented design pattern. Let’s start with the python version:
%%python
class HelloSayer:
def __init__(self, to): self.to = todef say(self):
"Do the saying"
print(f"Hello {self.to}!")
o = HelloSayer("Arjun")
o.say()
>> Hello Arjun!
And now in Mojo, we’ve got to deal with the strong type-checking:
struct HelloSayer:
var to: StringLiteralfn __init__(inout self, to: StringLiteral):
self.to = to
fn say(inout self):
print('Hello', self.to, '!')
var o = HelloSayer("Leela")
o.say()
>> Hello Leela !
So, there you have got a quite simple example of writing a function and a struct with a function in Mojo. While its very early days for the language I’m keen to see the way it things shape up over the subsequent 6 months (and onwards).
eşi eve bağlamak için http://www.medyumnazar.com