Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.

Classic structs use named fields. They are the most common Rust struct type and correspond closely to PHP classes with public properties.

Rust

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        username: String::from("someusername123"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
        active: true,
    };
    println!("Username: {}", user1.username);
    println!("Email: {}", user1.email);
    println!("Sign-in count: {}", user1.sign_in_count);
    println!("Active: {}", user1.active);
}

PHP

<?php
class User {
    public string $username;
    public string $email;
    public int $sign_in_count;
    public bool $active;
}

$user1 = new User();
$user1->username = 'someusername123';
$user1->email = '[email protected]';
$user1->sign_in_count = 1;
$user1->active = true;

echo "Username: {$user1->username}\n";
echo "Email: {$user1->email}\n";

Comparison

  • Rust: Fields accessed with dot notation; all fields required when constructing.
  • PHP: Properties accessed with ->; objects created with new and properties set individually or via constructor.
  • Rust: Field order in the struct definition is independent of instantiation order.
  • PHP: Typed properties (PHP 7.4+) enforce types similarly to Rust.

References

What's next

Next: Tuple structs.

From PHP to Rust — Rust Syntax and Functions