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

Rust’s struct update syntax (..existing) lets you create a new instance by copying most fields from another and overriding a few. PHP typically does this manually or with a copy/clone helper.

Rust

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

fn main() {
    let user1 = User {
        username: String::from("user1"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
        active: true,
    };
    let user2 = User {
        email: String::from("[email protected]"),
        ..user1  // Copy remaining fields from user1
    };
    println!("Username: {}", user2.username);
    println!("Email: {}", user2.email);
    // From `..user1` (not overridden above)
    println!("Sign-in count: {}", user2.sign_in_count);
    println!("Active: {}", user2.active);
}

PHP

<?php
class User {
    public function __construct(
        public string $username,
        public string $email,
        public int $sign_in_count,
        public bool $active,
    ) {}
}

$user1 = new User('user1', '[email protected]', 1, true);
$user2 = new User(
    $user1->username,
    '[email protected]',
    $user1->sign_in_count,
    $user1->active
);
echo "Username: {$user2->username}\n";
echo "Email: {$user2->email}\n";

Comparison

  • Rust: ..user1 copies remaining fields; ownership rules apply (e.g. String moves from user1).
  • PHP: Manually pass or copy properties; clone exists but does shallow copy.
  • Rust: Update syntax is concise and part of the language.
  • PHP: Often implemented with factory methods or a with* style API.

References

What's next

Next: Methods and associated functions.

From PHP to Rust — Rust Syntax and Functions