Hands On Generic Parameterization of Functions

Created: 12 February 2025  Modified: 12 February 2025

Mojo Parameterization is part of compile time code generation/modification.
We will try to keep our exploration of Parameters as shallow as possible so we can jump right in to writing compilable code. The goal is to provide enough understanding of Mojo Parameters to enable reading of documentation.

You will need a basic understanding of Traits which can be acquired reading Hands On Mojo Traits.

In other programming languages parameter and argument terminology is often used interchangeably. In Mojo the two are distincly different. Function arguments are used while the compiled code is running. Parameters are used while the code is being compiled.

For our code example we will create a function that focus on Parameters and Generics. Generics allow us to write generic code that will interact with multiple data types. As long as the data type implements the correct method. Below we have a contrived example that shows how generics work. The commented out code will not compile. You can uncomment it while you are playing with the code to better understand how traits, parameters and generics work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
trait WarmBlooded:
    fn is_warm_blooded(self) -> Bool:
        ...

trait ColdBlooded:
    fn is_cold_blooded(self) -> Bool:
        ...

@value
struct Cat:
    var name: String

    fn is_warm_blooded(self) -> Bool:
        return True

@value
struct Turtle:
    var name: String

    fn is_cold_blooded(self) -> Bool:
        return True

fn print_warm_blooded[T: WarmBlooded](warm_blood: T):
    print(warm_blood.is_warm_blooded())

fn print_cold_blooded[T: ColdBlooded](cold_blood: T):
    print(cold_blood.is_cold_blooded())

fn main():
    betsy = Cat("Betsy")
    samuel = Turtle("Samuel")
    print_warm_blooded(betsy)
    #print_cold_blooded(betsy)
    #print_warm_blooded(samuel)
    print_cold_blooded(samuel)
tags: mojo - mojolang - parameter - function
   Improve every day.