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

Tuple structs have unnamed fields identified by index. They give a type name to a tuple and are useful when you want a distinct type without named fields. PHP has no direct equivalent; arrays or objects with positional constructor args are used instead.

Use case: same shape, different meaning

(i32, i32, i32) could be RGB or a 3D size or anything, Rust treats those as the same type, so you could mix them up by accident. A tuple struct like Color or Dimensions is still “three i32s in order,” but the compiler knows Color is not Point and not a raw (i32, i32, i32). That’s useful for APIs: fn paint(c: Color) can’t be called with a Point by mistake. In PHP you’d usually use a class or named array keys to get a similar distinction.

Rust

struct Color(i32, i32, i32);
struct Point(i32, i32);

// Only accepts a Color, not a Point, not a plain (i32, i32, i32)
fn average_rgb(c: &Color) -> i32 {
    (c.0 + c.1 + c.2) / 3
}

fn main() {
    let black = Color(0, 0, 0);
    let white = Color(255, 255, 255);
    let origin = Point(0, 0);

    println!("Black: ({}, {}, {})", black.0, black.1, black.2);
    println!("Origin: ({}, {})", origin.0, origin.1);
    println!("Average of black={}, white={}", average_rgb(&black), average_rgb(&white));
}

PHP

<?php
// No tuple structs; use arrays or a simple class
class Color {
    public function __construct(
        public int $r,
        public int $g,
        public int $b,
    ) {}
}

$black = new Color(0, 0, 0);
echo "Black: ({$black->r}, {$black->g}, {$black->b})\n";

// Or array
$black = [0, 0, 0];
echo "Black: ({$black[0]}, {$black[1]}, {$black[2]})\n";

Comparison

  • Rust: Fields accessed as .0, .1, .2; each tuple struct is its own type.
  • PHP: Use arrays for positional data or classes with named properties.
  • Rust: Tuple structs are strongly typed; Color and (i32, i32, i32) are different types.
  • PHP: Arrays are untyped; constructor promotion can approximate positional arguments.

References

What's next

Next: Unit structs.

From PHP to Rust — Rust Syntax and Functions