Mojo Basics: Variables, Data Types, and Operators Explained

Mojo

Before building complex applications, it’s important to understand the basic building blocks of Mojo. This article covers variables, data types, and operators to help you write cleaner and more effective code.

Learn the Basics of Mojo Syntax

Mojo is a new programming language that offers Python-like syntax while introducing static typing and low-level performance features. In this article, we’ll explore how to declare variables, use data types, and perform basic operations, comparing them with Python where helpful.

Variable Declaration

In Mojo, variables are defined using the let keyword. You can also explicitly define their type:

let x = 10               # Type is inferred as Int
let y: Float64 = 3.14    # Type is explicitly declared

If you want to declare constants (values that cannot be reassigned), use the const keyword:

const z = "Hello Mojo"

Basic Data Types

  • Int, Int8, Int32: Integer types
  • Float32, Float64: Floating-point numbers
  • Bool: Boolean values (true / false)
  • String: Text values

Mojo allows you to choose the exact type for better memory control and performance.

Operators

Mojo supports arithmetic operators similar to Python:

OperatorDescriptionExample
+Addition1 + 2
-Subtraction5 - 3
*Multiplication4 * 2
/Division (float)7 / 2
//Floor Division7 // 2
%Modulo7 % 3
**Exponentiation2 ** 3

Bonus: Sneak Peek at Mojo Functions

In the next article, we’ll dive into defining functions in Mojo. Here’s a preview:

fn add(a: Int, b: Int) -> Int:
    return a + b

Mojo encourages static typing in function signatures for clarity and performance.

Summary

  • Use let or const for variable declarations
  • Leverage type annotations for performance and safety
  • Operators are mostly Python-compatible

Next time, we’ll continue with how to define and use functions in Mojo!

Comment

Copied title and URL