Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
Later in the course: Composite Types and the Module System revisits structs together with ownership of fields, modules and crates, and enums. Treat this chapter as the syntax-first pass; chapter 5 is the integration pass.
Structs are fundamental custom data types in both languages. They group related data into named fields. Rust has three kinds of structs: classic (named fields), tuple structs (unnamed positional fields), and unit structs (no fields). PHP uses classes for similar purposes, with struct-like behaviour via public properties.
Rust
// Three struct kinds: classic, tuple, unit
struct User { // Classic: named fields
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
struct Color(i32, i32, i32); // Tuple struct: unnamed fields
#[derive(Debug)]
struct AlwaysEqual; // Unit struct: no fields
fn main() {
let user = User {
username: String::from("ada"),
email: String::from("[email protected]"),
sign_in_count: 0,
active: true,
};
let black = Color(0, 0, 0);
let _marker = AlwaysEqual;
// Read fields so the compiler knows they're used (Debug alone can still warn)
println!(
"classic: {} <{}> sign_in_count={} active={}",
user.username, user.email, user.sign_in_count, user.active
);
println!("tuple struct: rgb({}, {}, {})", black.0, black.1, black.2);
println!("unit struct: {:?}", _marker);
}
PHP
<?php
// PHP uses classes; public properties approximate struct fields
class User {
public string $username;
public string $email;
public int $sign_in_count;
public bool $active;
}
Comparison
- Rust: Explicit
structkeyword; no methods required. Structs group data; methods live inimplblocks. - PHP: Uses
classfor data and behaviour; properties declare types with PHP 7.4+ typed properties. - Rust: Three variants (classic, tuple, unit) serve different use cases; PHP classes are the main composite type.
- Rust: Structs own or borrow data; PHP objects use reference semantics.
References
What's next
Next: Classic structs.
From PHP to Rust — Rust Syntax and Functions