DEV Community

Son DotCom ๐Ÿฅ‘๐Ÿ’™
Son DotCom ๐Ÿฅ‘๐Ÿ’™

Posted on • Edited on

Rust for Solana โ€“ EP04: Structs, Enums, Functions, Traits & Modules

Now that you understand the ownership model and data types in Rust, it's time to go deeper into how Rust lets us organize, abstract, and structure logic.

In this episode, youโ€™ll learn:

โœ… How to define and use structs

โœ… How to model data with enums

โœ… How to apply pattern matching

โœ… How to write functions and traits

โœ… How to organize your code with modules

These tools are the foundation for building scalable Solana smart contracts and apps in Rust.


๐Ÿงฑ Part 1: Structs in Rust

A struct in Rust is used to group related data.

โœจ Defining and Instantiating Structs

struct User {
    username: String,
    age: u8,
}

fn main() {
    let user = User {
        username: String::from("alice"),
        age: 30,
    };

    println!("User: {} is {} years old", user.username, user.age);
}
Enter fullscreen mode Exit fullscreen mode

โœจ Struct with Associated Function

impl User {
    fn is_adult(&self) -> bool {
        self.age >= 18
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”€ Part 2: Enums in Rust

Enums allow you to define a type by enumerating possible variants.

โœจ Example: Message Enum

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
}
Enter fullscreen mode Exit fullscreen mode

Each variant can carry data or none at all.

โœจ Matching Enums

fn process(msg: Message) {
    match msg {
        Message::Quit => println!("Quit"),
        Message::Move { x, y } => println!("Move to ({x}, {y})"),
        Message::Write(text) => println!("Write: {text}"),
    }
}
Enter fullscreen mode Exit fullscreen mode

Enums are powerful for representing state, commands, or network messages โ€” perfect for smart contracts.


๐ŸŽญ Part 3: Pattern Matching

match lets you run code based on pattern logic. It works with enums, primitives, tuples, structs, and more.

โœจ Match with Option<T>

fn maybe_double(val: Option<i32>) -> i32 {
    match val {
        Some(x) => x * 2,
        None => 0,
    }
}
Enter fullscreen mode Exit fullscreen mode

โœจ Match with Structs

let user = User {
    username: "Bob".into(),
    age: 25,
};

match user {
    User { age, .. } if age >= 18 => println!("Adult"),
    _ => println!("Minor"),
}
Enter fullscreen mode Exit fullscreen mode

You can destructure values inside match, if let, and while let for expressive flow control.


๐Ÿงฎ Part 4: Functions in Rust

Functions are reusable blocks of code defined using the fn keyword.

fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}
Enter fullscreen mode Exit fullscreen mode

โœจ Key Points

  • All parameters must have types.
  • Return type is defined using ->.
  • The last expression (without a ;) is returned.
fn add(a: i32, b: i32) -> i32 {
    a + b
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”Œ Part 5: Traits in Rust

Traits define shared behavior that types can implement.

โœจ Define a Trait

trait Summary {
    fn summarize(&self) -> String;
}
Enter fullscreen mode Exit fullscreen mode

โœจ Implement for Struct

impl Summary for User {
    fn summarize(&self) -> String {
        format!("{} ({})", self.username, self.age)
    }
}
Enter fullscreen mode Exit fullscreen mode

โœจ Use Traits in Functions

fn notify(item: &impl Summary) {
    println!("Notification: {}", item.summarize());
}
Enter fullscreen mode Exit fullscreen mode

Traits give Rust powerful polymorphism without runtime overhead.


๐Ÿ“ฆ Part 6: Modules in Rust

Modules let you split your code into organized files and control visibility.

โœจ Inline Module

mod greetings {
    pub fn hello() {
        println!("Hello!");
    }
}

fn main() {
    greetings::hello();
}
Enter fullscreen mode Exit fullscreen mode

โœจ File-based Modules

src/
โ”œโ”€โ”€ main.rs
โ””โ”€โ”€ utils.rs
Enter fullscreen mode Exit fullscreen mode

main.rs

mod utils;

fn main() {
    utils::welcome();
}
Enter fullscreen mode Exit fullscreen mode

utils.rs

pub fn welcome() {
    println!("Welcome to Rust for Solana!");
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“š Summary Table

Concept Description
struct Group related data into one logical unit
enum Represent multiple related variants
match Exhaustive pattern matching for control flow
fn Reusable functions with static typing
trait Define and share behavior across types
mod Organize and encapsulate logic across files

๐Ÿงช Practice Exercises

1. Define a Struct

Create a struct Product with name, price, and stock. Implement a method is_in_stock().

2. Enum Challenge

Create an enum OrderStatus with Pending, Shipped, Delivered. Match and print their status.

3. Trait Implementation

Define a Displayable trait with display(&self) -> String. Implement it for Product.

4. Module Exercise

Create a math module with add, subtract, multiply, and divide functions. Use them in main.

Top comments (0)