Skip to main content

Mojo 🔥 Test-Drive

Test-driving the new Mojo programming language. It’s a systems programming language with Python syntax, so we can now use our Python skills for systems programming with a minimal learning hill to climb.

Random Password Generator

# Usage: $ mojo build -march native randpass.mojo
#        $ ./randpass

from random import seed, random_ui64


fn generate_random_password() -> String:
    """Generate 21 character random password."""

    let selection: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@"

    var rand_pass: String = ""
    var password_length = 21

    seed()

    while password_length > 0:
        rand_pass += selection[random_ui64(0, selection.__len__() - 1).to_int()]
        password_length -= 1

    return rand_pass


fn main():
    print(generate_random_password())

Python inter-op version:

# Usage: mojo randpass.mojo

from python import Python
from python.object import PythonObject


fn generate_random_password() -> PythonObject:
    """Generate 21 character random password."""

    try:
        let random = Python.import_module("random")
        let string = Python.import_module("string")

        let selection = string.ascii_letters + string.digits + "#$%&@"

        var rand_pass: PythonObject = ""
        var password_length = 21

        while password_length > 0:
            rand_pass += random.choice(selection)
            password_length -= 1

        return rand_pass

    except Exception:
        return "Meh!"


fn main():
    print(generate_random_password())