Rust:Rust Structs and impl Blocks: Methods and Associated Functions
Rust•Methods & impl

Rust Structs and impl Blocks: Methods and Associated Functions

Learn method syntax (&self, &mut self) and associated functions like ServerNode::new().

Syntax

impl StructName { fn new() -> Self {} fn method(&self) {} }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&selfReceiverBorrows struct instance immutably.
&mut selfReceiverBorrows struct instance mutably.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

struct ServerNode {
    hostname: String,
    port: u16,
    is_active: bool,
}

impl ServerNode {
    // Associated function (constructor)
    fn new(host: &str, port: u16) -> Self {
        ServerNode {
            hostname: String::from(host),
            port,
            is_active: false,
        }
    }

    // Mutable method
    fn start(&mut self) {
        self.is_active = true;
        println!("[NODE] {}:{} is now active.", self.hostname, self.port);
    }

    // Immutable method
    fn status(&self) -> &str {
        if self.is_active { "ONLINE" } else { "OFFLINE" }
    }
}

fn main() {
    let mut node = ServerNode::new("api-primary", 8080);
    println!("Status before: {}", node.status());
    node.start();
    println!("Status after:  {}", node.status());
}
Expected Output:
Status before: OFFLINE
[NODE] api-primary:8080 is now active.
Status after:  ONLINE

How It Works: Step-by-Step

  • Lines 7-15: ServerNode::new constructor returns Self.
  • Lines 18-21: fn start(&mut self) mutates struct fields in place.
  • Lines 24-26: fn status(&self) borrows fields immutably.

Key Concepts

  • impl blocks associate methods with types.
  • Associated functions without self are called with :: syntax (e.g. Type::new()).
  • Methods with &self are called with dot syntax (e.g. instance.status()).

Common Mistake: Calling a &mut self method on an immutable struct variable

Methods with &mut self require the struct instance to be declared with let mut.

❌ Incorrect
let node = ServerNode::new(...);
node.start(); // Compile Error: cannot borrow as mutable
✅ Correct
let mut node = ServerNode::new(...);
node.start();

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler