Polyglot Artisan

PHP, Go and Rust, side by side

You already think in PHP. Each topic below shows the same task in all three languages, from first variable to async runtimes, with notes written for PHP developers and links to the exact docs page.

AspectPHPGoRust
TypingDynamic, optional type hints; declare(strict_types=1) per fileStatic, inferred with :=; no implicit conversionsStatic, inferred; strict, no implicit conversions
Runs asInterpreted (OPcache + JIT), one process per request under FPMCompiled to one native binary, long-running serverCompiled to one native binary, long-running server
MemoryRefcount + cycle GC, freed at end of requestTracing garbage collectorOwnership and borrowing; no GC
ErrorsExceptions, try / catchErrors are values: if err != nilResult<T, E> and the ? operator
Nullnull, ?->, ??nil plus zero valuesNo null: Option<T>
ConcurrencySeparate processes, queues, FibersGoroutines and channelsThreads, async/await with Tokio
PackagesComposer, PackagistGo modules, go getCargo, crates.io
Learning curveYou already know itA weekend to read, a month to be idiomaticWeeks to fight the borrow checker, then it clicks
ReleasesYearly, each NovemberEvery six months, February and AugustEvery six weeks

Versions covered

Code is written for the versions below and works on anything newer unless a snippet carries a version tag such as Go 1.27+. Latest releases checked December 5, 2026.

PHP

Written for
8.4
Latest release
8.6.0
Works on
PHP 8.4 and newer

Property hooks, asymmetric visibility and new without brackets are used freely. Newer features such as the PHP 8.5 pipe operator and PHP 8.6 partial application appear as "New in" notes. Release notes

Go

Written for
1.26
Latest release
1.27.4
Works on
Go 1.26 and newer

Generics, range-over-func iterators, wg.Go, new(expr) and errors.AsType are used freely. Go 1.27 additions such as generic methods and encoding/json/v2 appear as "New in" notes. Release notes

Rust

Written for
1.85, 2024 edition
Latest release
1.100.1
Works on
Rust 1.85 and newer

Every snippet uses the 2024 edition. Later additions such as let chains (1.88) appear as "New in" notes. Release notes

Basics

Syntax you already think in, translated: variables, strings, arrays, maps, control flow and functions. The big shift is that Go and Rust are compiled and statically typed, so the compiler catches what PHP would only find at runtime.

PHP is interpreted: you run the source file directly. Go and Rust compile to a native binary first, though go run and cargo run hide that step during development.

<?php
// hello.php
echo "Hello, world!\n";

// Run it:
//   php hello.php
// Or serve a folder:
//   php -S localhost:8000
// main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}

// go mod init example.com/hello
// go run .          compile + run (temp binary)
// go build -o hello && ./hello
RustRun ↗
// src/main.rs
fn main() {
    println!("Hello, world!"); // ! = macro call
}

// cargo new hello && cd hello
// cargo run              debug build + run
// cargo build --release  optimised binary
//   -> target/release/hello
  • Go. Every executable needs package main and a func main(). The output is a single (usually static) binary: no runtime to install on the server.
  • Rust. cargo is Composer + PHPUnit + the build tool in one. println! ends in ! because it is a macro, not a function.
  • Tip. Expect the first cargo build to be slow (it compiles every dependency). Later builds are incremental.

Suggest an edit to this topic

PHP variables are dynamic and always mutable. Go infers the type once and fixes it; Rust also infers it, and makes every binding immutable unless you write mut.

<?php
$name = "Ada";          // type follows the value
$name = 42;             // allowed: now an int
$count = 0;
$count++;

const MAX_USERS = 10;   // compile-time constant
define('APP_ENV', 'local');

[$a, $b] = [1, 2];      // destructuring
Go
var name string = "Ada" // explicit type
city := "London"        // := declares + infers
// city = 42             // compile error: string

var count int           // zero value: 0
count++

const MaxUsers = 10

a, b := 1, 2            // multiple assignment
a, b = b, a             // swap
_, _ = name, city       // unused vars won't compile
Rust
let name = "Ada";         // immutable by default
// name = "Bob";          // compile error

let mut count = 0;        // opt in to mutation
count += 1;

let total: u32 = 5;       // explicit type
let total = total * 2;    // shadowing: new binding

const MAX_USERS: u32 = 10; // type required

let (a, b) = (1, 2);      // destructuring
println!("{name} {count} {total} {a} {b}");
  • Go. Unused local variables and unused imports are compile errors in Go. Assign to _ to discard a value on purpose.
  • Go. := only works inside functions and needs at least one new variable on the left. At package level use var.
  • Rust. Shadowing (let x = x * 2;) creates a new variable, and can even change its type. It is idiomatic and different from mut.
  • Tip. Go has no ++ expression (x = y++ is invalid) and Rust has no ++ at all: use += 1.

Suggest an edit to this topic

PHP has one int and one float and quietly juggles types. Go and Rust have sized numeric types and never convert implicitly: you cast or parse, and parsing can fail.

<?php
declare(strict_types=1);

$i = 42;          // int (64-bit)
$f = 3.14;        // float
$ok = true;       // bool
$s = "7";

$n = (int) $s;            // 7
$n = intval("7 apples");  // 7, silently
$x = "5" + 3;             // 8: type juggling
var_dump(0 == "a");       // false in PHP 8

echo gettype($f);         // "double"
Go
import "strconv"

var i int = 42        // 64-bit on 64-bit CPUs
var small int8 = 127  // also int16/32/64, uint...
var f float64 = 3.14
var ok bool = true
var b byte = 'A'      // alias for uint8

total := float64(i) + f   // explicit conversion
n, err := strconv.Atoi("7")
if err != nil { /* "7 apples" fails */ }
s := strconv.Itoa(i)      // int -> "42"
_, _, _, _, _ = small, ok, b, n, s
_ = total
Rust
let i: i64 = 42;      // i8..i128, u8..u128
let idx: usize = 3;   // used for indexes/lengths
let f: f64 = 3.14;
let ok: bool = true;
let c: char = 'é';    // 4-byte Unicode scalar

let total = i as f64 + f;  // explicit cast
let n: i32 = "7".parse().unwrap();
let bad = "7 apples".parse::<i32>(); // Err(..)
let s = i.to_string();     // "42"
let fits: u8 = u8::try_from(300).unwrap_or(255);
println!("{idx} {ok} {c} {total} {n} {bad:?} {s} {fits}");
  • PHP. declare(strict_types=1) is the closest PHP gets: it stops scalar coercion at function boundaries, but "5" + 3 still works.
  • Go. int + int64 will not compile even though both are 64-bit. Mixing types always needs a conversion like int64(x).
  • Rust. as casts can truncate silently (300_i32 as u8 is 44). Prefer try_from / try_into when a value might not fit.
  • Watch out. Integer overflow panics in Rust debug builds and wraps in release builds. Go always wraps. PHP turns big ints into floats.

Suggest an edit to this topic

All three store strings as bytes and treat UTF-8 as the norm, so "length" means bytes unless you ask for characters. Rust adds a split PHP never had: owned String and borrowed &str.

<?php
$name = "Zoë";
$greet = "Hi " . $name;           // concat
$msg = "Hello {$name}!";          // interpolation
$line = sprintf("%-6s|%05.2f", $name, 3.14159);

strlen($name);            // 4 (bytes)
mb_strlen($name);         // 3 (chars)
str_contains($msg, "lo"); // true
strtoupper("abc");        // "ABC"
explode(",", "a,b,c");    // ["a","b","c"]
trim("  hi  ");           // "hi"
str_replace("Hi", "Yo", $greet);
Go
import ("fmt"; "strings"; "unicode/utf8")

name := "Zoë"
greet := "Hi " + name
msg := fmt.Sprintf("Hello %s!", name) // no interpolation
line := fmt.Sprintf("%-6s|%05.2f", name, 3.14159)

fmt.Println(len(name))         // 4 (bytes)
utf8.RuneCountInString(name)   // 3 (runes)
strings.Contains(msg, "lo")    // true
strings.ToUpper("abc")
strings.Split("a,b,c", ",")    // []string
strings.TrimSpace("  hi  ")
strings.ReplaceAll(greet, "Hi", "Yo")
var sb strings.Builder        // fast appends
sb.WriteString(line)
Rust
let name = "Zoë";                 // &str: borrowed slice
let greet = format!("Hi {name}"); // String: owned
let mut s = String::from("Hi ");
s.push_str(name);                 // grow in place
let line = format!("{:<6}|{:05.2}", name, 3.14159);

name.len();                  // 4 (bytes)
name.chars().count();        // 3 (chars)
greet.contains("Zo");        // true
"abc".to_uppercase();
let parts: Vec<&str> = "a,b,c".split(',').collect();
"  hi  ".trim();
greet.replace("Hi", "Yo");
println!("{line} {parts:?}");
  • Go. Go has no string interpolation: use fmt.Sprintf with %s, %d, %v (any value) and %+v (struct with field names).
  • Rust. Rule of thumb: take &str as a function parameter, return or store String. &String converts to &str automatically.
  • Rust. format!("{name}") captures variables by name since Rust 1.58, which is close to PHP's "{$name}".
  • Watch out. Slicing by byte index ($s[0], s[0:1], &s[0..1]) can cut a multi-byte character in half. In Rust that panics at runtime.

Suggest an edit to this topic

A PHP array is one structure that does everything. Go splits it into fixed arrays and growable slices; Rust into fixed arrays and growable Vec<T>. Each holds one element type.

<?php
$nums = [3, 1, 2];
$nums[] = 4;                 // append
count($nums);                // 4
$first = $nums[0];
$part = array_slice($nums, 1, 2); // [1, 2]
sort($nums);                 // in place
in_array(2, $nums, true);    // true
array_pop($nums);            // 4
$mixed = [1, "two", 3.0];    // any types
Go
import ("slices"; "fmt")

nums := []int{3, 1, 2}       // slice
nums = append(nums, 4)       // returns new slice
fmt.Println(len(nums))       // 4
first := nums[0]
part := nums[1:3]            // [1 2] shares memory
slices.Sort(nums)            // Go 1.21+
slices.Contains(nums, 2)     // true
last := nums[len(nums)-1]
nums = nums[:len(nums)-1]    // "pop"

fixed := [3]int{1, 2, 3}     // array: size is part of type
buf := make([]int, 0, 100)   // len 0, capacity 100
fmt.Println(first, part, last, fixed, buf) // part is now [2 3]
Rust
let mut nums = vec![3, 1, 2];   // Vec<i32>
nums.push(4);                   // append
nums.len();                     // 4
let first = nums[0];            // panics if out of range
let maybe = nums.get(10);       // Option<&i32>: None
let part = &nums[1..3];         // slice &[i32]
println!("{first} {maybe:?} {part:?}");
nums.sort();
nums.contains(&2);              // true
let last = nums.pop();          // Option<i32>

let fixed: [i32; 3] = [1, 2, 3]; // array
let buf: Vec<i32> = Vec::with_capacity(100);
println!("{last:?} {fixed:?} {}", buf.len());
  • PHP. PHP arrays are ordered hash maps underneath; lists and maps are the same type. In Go and Rust they are different types: lists here, maps in the next topic.
  • Go. Always write s = append(s, x). A sub-slice like nums[1:3] shares the same backing array, so writes through it change the original.
  • Rust. nums[10] panics; nums.get(10) returns None. Use .get() wherever an index might be missing.
  • Tip. Mixed-type lists need an interface ([]any) in Go or an enum in Rust. Usually it means you want a struct instead.
  • Tip. New in PHP 8.5: array_first() and array_last() return the first/last value or null when empty, close to Rust's first() / last() returning an Option.

Suggest an edit to this topic

Key-value lookups work the same way, but PHP keeps insertion order while Go maps and Rust HashMap do not. A missing key gives a zero value in Go and None in Rust, never a warning.

<?php
$ages = ["ada" => 36, "linus" => 54];
$ages["grace"] = 85;            // insert/update

$a = $ages["bob"] ?? 0;         // default if missing
isset($ages["ada"]);            // true
unset($ages["linus"]);          // delete

foreach ($ages as $name => $age) {
    echo "$name is $age\n";     // insertion order
}
array_keys($ages);
Go
ages := map[string]int{"ada": 36, "linus": 54}
ages["grace"] = 85            // insert/update

a := ages["bob"]              // 0: zero value
age, ok := ages["ada"]        // "comma ok" idiom
if ok { fmt.Println(age) }
delete(ages, "linus")

for name, age := range ages { // RANDOM order
    fmt.Printf("%s is %d\n", name, age)
}
keys := slices.Sorted(maps.Keys(ages)) // Go 1.23+
_, _ = a, keys

var m map[string]int  // nil map: reads ok,
// m["x"] = 1         // writes panic! use make()
m = make(map[string]int)
m["x"] = 1            // fine now
Rust
use std::collections::HashMap;

let mut ages = HashMap::from([("ada", 36), ("linus", 54)]);
ages.insert("grace", 85);           // insert/update

let a = ages.get("bob").copied().unwrap_or(0);
if let Some(age) = ages.get("ada") {
    println!("{age}");
}
ages.remove("linus");
*ages.entry("ada").or_insert(0) += 1; // upsert

for (name, age) in &ages {          // arbitrary order
    println!("{name} is {age}");
}
// Need sorted keys? use BTreeMap instead.
println!("{a}");
  • Watch out. Never rely on map order in Go or Rust. Sort the keys, or in Rust use BTreeMap (sorted) or the indexmap crate (insertion order like PHP).
  • Go. The v, ok := m[k] form tells "missing" apart from "present with zero value". Writing to a nil map panics, so create maps with a literal or make.
  • Rust. The entry() API does "insert if missing, else update" in one lookup, like $a[$k] = ($a[$k] ?? 0) + 1.

Suggest an edit to this topic

Go has no ternary and no match, only if and a switch that does not fall through. Rust's if and match are expressions that return values, and match must cover every case.

<?php
$score = 72;
if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 70) {
    $grade = "B";
} else {
    $grade = "C";
}

$label = $score > 50 ? "pass" : "fail";
$nick = $user->nick ?? "guest";

$msg = match (true) {
    $score >= 90 => "great",
    $score >= 70 => "good",
    default => "keep going",
};
Go
score := 72
var grade string
if score >= 90 {
    grade = "A"
} else if score >= 70 {
    grade = "B"
} else {
    grade = "C"
}

label := "fail" // no ternary operator
if score > 50 { label = "pass" }

if n := len(grade); n > 0 { // init statement
    fmt.Println(n)
}

switch { // no fallthrough, no break needed
case score >= 90:
    fmt.Println("great")
case score >= 70:
    fmt.Println("good")
default:
    fmt.Println("keep going")
}
_ = label
Rust
let score = 72;
let grade = if score >= 90 {
    "A"
} else if score >= 70 {
    "B"
} else {
    "C"
}; // if is an expression

let label = if score > 50 { "pass" } else { "fail" };
let nick = user.nick.as_deref().unwrap_or("guest");

let msg = match score {
    90..=100 => "great",
    70..=89 => "good",
    _ => "keep going", // must be exhaustive
};
println!("{grade} {label} {nick} {msg}");
  • Go. if v := f(); v > 0 { } scopes v to the if. You will see it constantly as if err := do(); err != nil { }.
  • Go. Go switch cases stop automatically. Use fallthrough explicitly if you really want PHP switch behaviour.
  • Rust. Conditions must be bool (in Go too): if count { } will not compile. There is no truthiness for 0, "" or empty arrays.
  • PHP. PHP 8 match is the closest relative of Rust match: strict comparison, returns a value, and throws UnhandledMatchError where Rust refuses to compile.
  • Tip. New in Rust 1.88 (2024 edition): let chains. if let Some(n) = user.nick.as_deref() && !n.is_empty() { } replaces a nested if let + if.

Suggest an edit to this topic

Loops

Go has a single loop keyword, for, which also covers while and foreach. Rust has loop, while and for over iterators, and a loop can break with a value.

<?php
for ($i = 0; $i < 3; $i++) { echo $i; }

foreach (["a", "b"] as $idx => $item) {
    echo "$idx: $item\n";
}

$n = 10;
while ($n > 1) { $n = intdiv($n, 2); }

// no loop labels: count levels instead
foreach ([1, 2] as $x) {
    foreach ([1, 2] as $y) {
        if ($y === 2) continue 2; // next $x
        if ($x === 2) break 2;    // leave both
    }
}
Go
for i := 0; i < 3; i++ { fmt.Print(i) }

for i := range 3 { fmt.Print(i) } // Go 1.22+: 0,1,2

for idx, item := range []string{"a", "b"} {
    fmt.Printf("%d: %s\n", idx, item)
}

n := 10
for n > 1 { n /= 2 } // the "while" loop

for { break }        // infinite loop

outer:
for _, x := range []int{1, 2} {
    for _, y := range []int{1, 2} {
        if y == 2 { continue outer }
        if x == 2 { break outer }
    }
}
Rust
for i in 0..3 { print!("{i}"); }       // 0,1,2
for i in (0..=10).step_by(5) { print!("{i}"); }

for (idx, item) in ["a", "b"].iter().enumerate() {
    println!("{idx}: {item}");
}

let mut n = 10;
while n > 1 { n /= 2; }

let mut tries = 0;
let found = loop {                    // loop returns a value
    tries += 1;
    if tries == 3 { break tries * 10; }
};

'outer: for x in [1, 2] {
    for y in [1, 2] {
        if y == 2 { continue 'outer; }
        if x == 2 { break 'outer; }
    }
}
println!("{found}");
  • Go. range gives index and value for slices, key and value for maps, and runes (not bytes) for strings. Use _ to skip the index.
  • Go. Since Go 1.22 each loop iteration gets a fresh variable, so closures capturing i inside a loop behave as you would expect.
  • Rust. for x in v moves (consumes) the vector. Write for x in &v to borrow it and keep using v afterwards.
  • Tip. Labels replace PHP's break 2: name the outer loop and break or continue it by name.

Suggest an edit to this topic

Types are mandatory on Go and Rust parameters. Neither has default values or named arguments. Go returns multiple values where PHP returns an array, Rust returns a tuple, and both use option structs or builders for "optional" arguments.

<?php
function greet(string $name, string $greeting = "Hello"): string
{
    return "$greeting, $name!";
}
greet("Ada");
greet(greeting: "Hi", name: "Ada");   // named args

function divmod(int $a, int $b): array
{
    return [intdiv($a, $b), $a % $b];
}
[$q, $r] = divmod(7, 2);

function sum(int ...$nums): int { return array_sum($nums); }
sum(1, 2, 3);
sum(...[1, 2]);                       // spread
Go
func greet(name, greeting string) string {
    if greeting == "" { greeting = "Hello" } // "default"
    return greeting + ", " + name + "!"
}

func divmod(a, b int) (int, int) { // multiple returns
    return a / b, a % b
}

func sum(nums ...int) int {        // variadic
    total := 0
    for _, n := range nums { total += n }
    return total
}

func main() {
    greet("Ada", "")
    q, r := divmod(7, 2)
    sum(1, 2, 3)
    sum([]int{1, 2}...)            // spread a slice
    fmt.Println(q, r)
}
RustRun ↗
fn greet(name: &str, greeting: Option<&str>) -> String {
    let g = greeting.unwrap_or("Hello"); // "default"
    format!("{g}, {name}!")             // no ; = return
}

fn divmod(a: i32, b: i32) -> (i32, i32) { // tuple
    (a / b, a % b)
}

fn sum(nums: &[i32]) -> i32 { // slice instead of variadic
    nums.iter().sum()
}

fn main() {
    greet("Ada", None);
    greet("Ada", Some("Hi"));
    let (q, r) = divmod(7, 2);
    let total = sum(&[1, 2, 3]);
    println!("{q} {r} {total}");
}
  • Rust. The last expression without a semicolon is the return value. Adding ; turns it into a statement and the function returns () (a common first compile error).
  • Go. Returning (value, error) is the core Go idiom; you will see it on almost every function that can fail.
  • Tip. For many optional settings, Go uses an options struct or "functional options" (NewServer(WithPort(80))); Rust uses a builder or ..Default::default().
  • Rust. Rust has no variadic functions; macros like println! and vec! fill that gap. Take a slice &[T] instead.

Suggest an edit to this topic

PHP closures copy captured variables unless you write use (&$x); arrow functions capture by value automatically. Go closures always capture by reference. Rust picks borrow or move for you, and move forces ownership into the closure.

<?php
$tax = 0.2;
$withTax = function (float $p) use ($tax): float {
    return $p * (1 + $tax);   // $tax copied in
};
$double = fn(int $x) => $x * 2; // auto-captures by value

$count = 0;
$inc = function () use (&$count) { $count++; };
$inc(); $inc();               // $count === 2

array_map($double, [1, 2, 3]); // [2, 4, 6]
$fn = strlen(...);             // first-class callable
Go
tax := 0.2
withTax := func(p float64) float64 {
    return p * (1 + tax) // captures tax by reference
}

count := 0
inc := func() { count++ } // mutates outer count
inc(); inc()              // count == 2

// functions are values: pass and return them
makeAdder := func(n int) func(int) int {
    return func(x int) int { return x + n }
}
add5 := makeAdder(5)
fmt.Println(withTax(100), count, add5(1))
Rust
let tax = 0.2;
let with_tax = |p: f64| p * (1.0 + tax); // borrows tax

let mut count = 0;
let mut inc = || count += 1;  // mutable borrow
inc(); inc();
println!("{count}");          // 2

let doubled: Vec<i32> = [1, 2, 3].iter().map(|x| x * 2).collect();

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n            // move: closure owns n
}
let add5 = make_adder(5);
println!("{} {doubled:?} {}", with_tax(100.0), add5(1));
  • Go. Go closures see later changes to captured variables. That is the opposite of PHP's default use ($x), which copies the value at creation time.
  • Rust. Closures implement Fn (reads), FnMut (mutates) or FnOnce (consumes). Use move when the closure outlives the scope, for example when you hand it to a thread.
  • Rust. While inc holds a mutable borrow of count, you cannot read count. The borrow ends after the closure's last use.
  • Tip. New in PHP 8.6: partial function application. $hasLo = str_contains(?, "lo"); returns a Closure waiting for the missing argument, like makeAdder(5) above.

Suggest an edit to this topic

PHP lets almost anything be null. Go has nil only for pointers, slices, maps, interfaces, channels and function values; other types get a zero value. Rust has no null at all: absence is Option<T>, and the compiler makes you handle it.

<?php
function findUser(int $id): ?User
{
    return $id === 1 ? new User("Ada") : null;
}

$user = findUser(2);
$name = $user?->name ?? "guest"; // nullsafe + default

if ($user !== null) {
    echo $user->name;
}

$city = $user?->address?->city;  // null if any link is null
Go
type User struct {
    Name string
    Nick *string // optional field: nil when unset
}

func findUser(id int) *User { // pointer can be nil
    if id == 1 { return &User{Name: "Ada", Nick: new("ada")} }
    return nil
}

func main() {
    user := findUser(2)
    name := "guest"
    if user != nil { // no ?-> operator
        name = user.Name
    }

    var s string // "" (zero value, not nil)
    var n int    // 0
    var u *User  // nil
    // u.Name    // runtime panic: nil pointer
    fmt.Println(name, s, n, u)
}
Rust
struct User { name: String }

fn find_user(id: u32) -> Option<User> {
    if id == 1 { Some(User { name: "Ada".into() }) } else { None }
}

let user = find_user(2);
let name = user.as_ref().map(|u| u.name.as_str()).unwrap_or("guest");

if let Some(u) = &user {      // handle the Some case
    println!("{}", u.name);
}

fn first_char(id: u32) -> Option<char> {
    let u = find_user(id)?;   // ? returns None early
    u.name.chars().next()
}
println!("{name} {:?}", first_char(1));
  • Go. Zero values replace most nulls: "", 0, false, empty struct. Use a pointer (*string) or a sql.Null* type only when you must tell "unset" apart from zero.
  • Rust. Option<T> is an enum: Some(value) or None. Learn map, unwrap_or, and_then, if let and ?. Avoid .unwrap() outside tests and prototypes.
  • Watch out. Go nil pointer dereference is a runtime panic, the equivalent of PHP's "Call to a member function on null". Rust rules this out at compile time.
  • Go. new("ada") makes a pointer to a copy of the value, so an optional pointer field fills in one step without a temporary variable.

Suggest an edit to this topic

The building blocks of a command-line tool. Go's os and bufio and Rust's std::env and std::io replace $argv, fgets(STDIN) and exit().

<?php
// php greet.php Ada
$name = $argv[1] ?? null;   // $argv[0] = script name
if ($name === null) {
    fwrite(STDERR, "usage: greet.php NAME\n");
    exit(1);                // non-zero = failure
}

echo "Age? ";
$age = (int) trim(fgets(STDIN));

printf("%s is %d\n", $name, $age);
exit(0);
Go
import ("bufio"; "fmt"; "os"; "strconv"; "strings")

func main() {
    if len(os.Args) < 2 { // os.Args[0] = program
        fmt.Fprintln(os.Stderr, "usage: greet NAME")
        os.Exit(1)
    }
    name := os.Args[1]

    fmt.Print("Age? ")
    line, _ := bufio.NewReader(os.Stdin).ReadString('\n')
    age, err := strconv.Atoi(strings.TrimSpace(line))
    if err != nil {
        fmt.Fprintln(os.Stderr, "not a number")
        os.Exit(1)
    }
    fmt.Printf("%s is %d\n", name, age)
}
RustRun ↗
use std::{env, io::{self, Write}, process};

fn main() {
    let args: Vec<String> = env::args().collect();
    let Some(name) = args.get(1) else { // let-else
        eprintln!("usage: greet NAME");
        process::exit(1);
    };

    print!("Age? ");
    io::stdout().flush().unwrap(); // print! does not flush
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("read failed");
    let age: u32 = match line.trim().parse() {
        Ok(n) => n,
        Err(_) => { eprintln!("not a number"); process::exit(1) }
    };
    println!("{name} is {age}");
}
  • Go. For real flags use the standard flag package, or cobra for subcommands (it is what Artisan-style CLIs in Go use).
  • Rust. clap with #[derive(Parser)] is the standard for argument parsing. eprintln! writes to stderr like fwrite(STDERR, ...).
  • Tip. os.Exit and process::exit skip deferred calls and destructors. Return from main normally when you can; Rust's main can also return Result.

Suggest an edit to this topic

Intermediate

Types, errors, modules and the everyday standard library. This is where the three stop looking alike: Go and Rust have no classes or exceptions, and Rust's ownership rules show up in every method signature.

PHP bundles data and behaviour in a class. Go and Rust declare the data (a struct) and attach methods separately, and the receiver says whether a method can change the value.

<?php
class Counter
{
    private int $count = 0;

    public function increment(): void
    {
        $this->count++;
    }

    public function value(): int
    {
        return $this->count;
    }
}

$c = new Counter();
$c->increment();
echo $c->value(); // 1
Go
type Counter struct {
    count int // lowercase = unexported (package-private)
}

// Pointer receiver: can mutate the struct
func (c *Counter) Increment() { c.count++ }

// Value receiver: works on a copy, read-only use
func (c Counter) Value() int { return c.count }

func main() {
    c := Counter{}         // no "new" keyword needed
    c.Increment()          // Go takes &c for you
    fmt.Println(c.Value()) // 1
}
RustRun ↗
struct Counter {
    count: u32,
}

impl Counter {
    fn increment(&mut self) { self.count += 1; } // mutable borrow
    fn value(&self) -> u32 { self.count }        // shared borrow
}

fn main() {
    let mut c = Counter { count: 0 }; // binding must be mut
    c.increment();
    println!("{}", c.value()); // 1
}
  • Go. No $this: the receiver is a named parameter (c). The snippet mixes both to show the difference; in real code, if any method needs a pointer receiver, make them all pointer receivers.
  • Rust. &self is a read-only $this, &mut self a mutating one, and plain self consumes the value so it cannot be used afterwards.
  • Watch out. PHP objects are passed by handle. Go structs are copied on assignment and Rust structs are moved, so $b = $a thinking does not carry over.

Suggest an edit to this topic

PHP has __construct, public/private and readonly. Go uses a plain NewX function and decides visibility by the first letter of a name. Rust uses a new() convention, pub, and the Default trait instead of default arguments.

<?php
final class User
{
    public function __construct(
        public readonly string $email,
        private string $role = 'member',
    ) {}

    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }
}

$u = new User('ada@example.com');
echo $u->email;     // ok
// $u->email = 'x'; // Error: readonly property
Go
package user

type User struct {
    Email string // Capitalised = exported (public)
    role  string // lowercase = package-private
}

// Constructor by convention: a function named New / NewUser
func New(email string) *User {
    return &User{Email: email, role: "member"}
}

func (u *User) IsAdmin() bool { return u.role == "admin" }

// elsewhere:
// u := user.New("ada@example.com")
// u.role  -> compile error outside package user
RustRun ↗
pub struct User {
    pub email: String, // public field
    role: String,      // private to this module
}

impl User {
    pub fn new(email: impl Into<String>) -> Self {
        Self { email: email.into(), role: "member".into() }
    }
    pub fn is_admin(&self) -> bool { self.role == "admin" }
}

#[derive(Debug, Default)]
pub struct Settings { pub per_page: u32, pub dark_mode: bool }

fn main() {
    let u = User::new("ada@example.com");
    // "optional args": set some fields, default the rest
    let s = Settings { per_page: 20, ..Default::default() };
    println!("{} {} {:?}", u.email, u.is_admin(), s);
}
  • Go. Visibility is per package, not per type. Any code in the same package can touch role.
  • Go. Zero values are valid: User{} compiles with empty fields. Design types so the zero value is useful, or force callers through New.
  • Rust. Fields are immutable unless the binding is mut, so there is no readonly keyword. Default plus ..Default::default() replaces optional constructor parameters.
  • Tip. For many optional settings, both Go (functional options) and Rust (builder pattern) use a dedicated pattern instead of long constructors.

Suggest an edit to this topic

All three let a function accept anything with the right methods. PHP and Rust require you to declare it (implements, impl Trait for); Go interfaces are satisfied automatically.

<?php
interface Notifier
{
    public function send(string $to, string $msg): void;
}

final class EmailNotifier implements Notifier // explicit
{
    public function send(string $to, string $msg): void
    {
        echo "Email to {$to}: {$msg}\n";
    }
}

function alert(Notifier $n): void
{
    $n->send('ops@example.com', 'Disk almost full');
}

alert(new EmailNotifier());
Go
type Notifier interface {
    Send(to, msg string) error
}

type EmailNotifier struct{}

// No "implements": having the method is enough
func (EmailNotifier) Send(to, msg string) error {
    fmt.Printf("Email to %s: %s\n", to, msg)
    return nil
}

func Alert(n Notifier) error {
    return n.Send("ops@example.com", "Disk almost full")
}

var _ Notifier = EmailNotifier{} // compile-time check idiom

func main() { _ = Alert(EmailNotifier{}) }
RustRun ↗
trait Notifier {
    fn send(&self, to: &str, msg: &str);
}

struct EmailNotifier;

impl Notifier for EmailNotifier { // explicit, like implements
    fn send(&self, to: &str, msg: &str) {
        println!("Email to {to}: {msg}");
    }
}

// Static dispatch: compiled once per concrete type
fn alert(n: &impl Notifier) { n.send("ops@example.com", "Disk almost full"); }

// Dynamic dispatch: closest to a PHP interface type hint
fn alert_all(list: &[Box<dyn Notifier>]) {
    for n in list { n.send("ops@example.com", "Disk almost full"); }
}

fn main() {
    alert(&EmailNotifier);
    alert_all(&[Box::new(EmailNotifier)]);
}
  • Go. Go style: keep interfaces small (one or two methods, like io.Reader) and declare them where they are used, not next to the implementation. "Accept interfaces, return structs."
  • Rust. impl Trait is generic and resolved at compile time; dyn Trait is a runtime vtable like PHP. You can also implement your trait for types you do not own, such as String.
  • Laravel. Laravel's container binds interface to implementation for you. In Go and Rust you usually pass the implementation in explicitly through a constructor.

Suggest an edit to this topic

PHP code leans on extends, abstract classes and traits. Neither Go nor Rust has class inheritance: Go embeds structs to reuse fields and methods, Rust combines composition with default trait methods.

<?php
trait Timestamps
{
    public ?string $createdAt = null;
    public function touch(): void { $this->createdAt = date('c'); }
}

abstract class Model
{
    abstract public function table(): string;
    public function describe(): string { return "Model on {$this->table()}"; }
}

final class Post extends Model
{
    use Timestamps;
    public function table(): string { return 'posts'; }
}

$p = new Post();
$p->touch();
echo $p->describe();
Go
type Timestamps struct {
    CreatedAt time.Time
}

func (t *Timestamps) Touch() { t.CreatedAt = time.Now() }

type Post struct {
    Timestamps // embedded: fields and methods are promoted
    Title string
}

func main() {
    p := &Post{Title: "Hello"}
    p.Touch()                // promoted from Timestamps
    fmt.Println(p.CreatedAt) // same as p.Timestamps.CreatedAt
}

// Embedding is not inheritance: a Post is not a Timestamps,
// and there is no parent:: or overridable "virtual" method.
RustRun ↗
trait Model {
    fn table(&self) -> &'static str;   // required ("abstract")
    fn describe(&self) -> String {      // default method
        format!("Model on {}", self.table())
    }
}

#[derive(Default)]
struct Timestamps { created_at: Option<u64> }

#[derive(Default)]
struct Post { title: String, ts: Timestamps } // has-a, not is-a

impl Model for Post {
    fn table(&self) -> &'static str { "posts" }
}

fn main() {
    let p = Post { title: "Hello".into(), ..Default::default() };
    println!("{} {} {:?}", p.title, p.describe(), p.ts.created_at);
}
  • Tip. Swap "is-a" for "has-a" plus interfaces/traits. Most Laravel-style base classes become a small struct you embed or hold as a field.
  • Go. Embedding is the closest thing to a PHP trait: promoted methods, zero boilerplate. An embedded type's method cannot call back into the outer type.
  • Rust. Default trait methods are like concrete methods on an abstract class, but traits cannot hold fields: shared data lives in a struct you compose in.

Suggest an edit to this topic

Enums

PHP 8.1 enums are a fixed set of cases with methods. Go has no enum type, only typed constants with iota. Rust enums are far more powerful: each variant can carry its own data, and match must cover every one.

<?php
enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';

    public function label(): string
    {
        return match ($this) {
            Status::Draft => 'Draft',
            Status::Published => 'Live',
            Status::Archived => 'Archived',
        };
    }
}

$s = Status::from('published');
echo $s->label(); // Live
Go
type Status int

const (
    Draft     Status = iota // 0
    Published               // 1
    Archived                // 2
)

func (s Status) String() string { // fmt.Stringer
    switch s {
    case Draft:
        return "Draft"
    case Published:
        return "Live"
    case Archived:
        return "Archived"
    }
    return "Unknown"
}

func main() {
    fmt.Println(Published)  // Live (fmt calls String())
    fmt.Println(Status(42)) // Unknown: any int is accepted
}
RustRun ↗
#[derive(Debug, Clone, PartialEq)]
enum Status {
    Draft,
    Published { at: String },           // variants carry data
    Archived { reason: Option<String> },
}

impl Status {
    fn label(&self) -> &str {
        match self {                     // must cover every variant
            Status::Draft => "Draft",
            Status::Published { .. } => "Live",
            Status::Archived { .. } => "Archived",
        }
    }
}

fn main() {
    let s = Status::Published { at: "2026-12-05".into() };
    println!("{}", s.label());
    if let Status::Published { at } = &s { println!("since {at}"); }
}
  • Go. The compiler does not check that a switch covers every constant, and Status(42) is legal. The exhaustive linter (in golangci-lint) closes that gap.
  • Rust. Option and Result are ordinary enums. Adding a variant breaks every non-exhaustive match, so the compiler lists each place you need to update.
  • PHP. Status::from() / tryFrom() become FromStr / TryFrom impls in Rust; serde can map enum variants to strings for you.

Suggest an edit to this topic

PHP throws exceptions and catches them somewhere up the stack. Go returns an error value as the last result and you check it immediately. Rust returns Result<T, E> and the ? operator passes errors up in one character.

<?php
final class UserNotFound extends RuntimeException {}

function findUser(int $id): array
{
    $users = [1 => ['name' => 'Ada']];
    return $users[$id] ?? throw new UserNotFound("user {$id}");
}

try {
    $user = findUser(2);
} catch (UserNotFound $e) {
    echo 'Not found: ' . $e->getMessage();
} finally {
    echo "\ndone";
}
Go
type UserNotFound struct{ ID int } // a typed error

func (e *UserNotFound) Error() string { return fmt.Sprintf("user %d not found", e.ID) }

func FindUser(id int) (string, error) {
    users := map[int]string{1: "Ada"}
    name, ok := users[id]
    if !ok {
        return "", fmt.Errorf("lookup: %w", &UserNotFound{ID: id}) // wrap
    }
    return name, nil
}

func main() {
    name, err := FindUser(2)
    if e, ok := errors.AsType[*UserNotFound](err); ok { // catch (UserNotFound $e)
        fmt.Println("Not found:", e.ID) // searches the wrap chain
        return
    }
    fmt.Println(name)
}
RustRun ↗
use std::{collections::HashMap, fmt};

#[derive(Debug)]
enum UserError { NotFound(u32) }

impl fmt::Display for UserError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self { UserError::NotFound(id) => write!(f, "user {id} not found") }
    }
}
impl std::error::Error for UserError {}

fn find_user(id: u32) -> Result<String, UserError> {
    let users = HashMap::from([(1, "Ada".to_string())]);
    users.get(&id).cloned().ok_or(UserError::NotFound(id))
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let name = find_user(2)?; // early-return on Err
    println!("{name}");
    Ok(())
}

fn main() {
    if let Err(e) = run() { eprintln!("Error: {e}"); }
}
  • Go. if err != nil { return ..., err } is normal Go, not a smell. Wrap with %w to add context; errors.AsType pulls a typed error out of the chain. For a fixed error value, declare a sentinel (var ErrNotFound = errors.New("not found")) and test it with errors.Is(err, ErrNotFound).
  • Go. panic/recover exist but are for programmer bugs, not control flow. Do not use them as exceptions.
  • Rust. ? converts and returns the error for you. .unwrap() and .expect() crash on Err: fine in tests and prototypes, a bug in production paths.
  • Tip. Real Rust projects drop the boilerplate above: thiserror derives error enums for libraries, anyhow gives apps one catch-all error with context.

Suggest an edit to this topic

PHP maps namespaces to folders through Composer's PSR-4 autoloader. In Go a directory is a package, imported by module path. In Rust you declare the module tree yourself with mod, and files are not loaded unless declared.

<?php
// src/Billing/Invoice.php   (composer.json: "App\\": "src/")
namespace App\Billing;

use App\Support\Money;        // import a class
use function App\Support\format_money;

final class Invoice
{
    public function __construct(private Money $total) {}

    public function label(): string
    {
        return format_money($this->total);
    }
}

// elsewhere:
// use App\Billing\Invoice;
// $i = new Invoice(new Money(1000));
Go
// go.mod:  module example.com/shop
//
// shop/
//   main.go             package main
//   billing/invoice.go  package billing
//   internal/money/     importable only inside example.com/shop

// billing/invoice.go
package billing

import "example.com/shop/internal/money"

type Invoice struct {
    Total money.Money // exported: capital letters
}

func (i Invoice) Label() string { return i.Total.Format() }

// main.go
// import "example.com/shop/billing"
// inv := billing.Invoice{Total: money.New(1000)}
Rust
// src/main.rs         crate root
// src/billing/mod.rs  (or src/billing.rs)
// src/billing/invoice.rs

// src/main.rs
mod billing;                     // files are not auto-loaded
use billing::invoice::Invoice;

fn main() {
    let i = Invoice::new(1000);
    println!("{}", i.total());
}

// src/billing/mod.rs
pub mod invoice;

// src/billing/invoice.rs
pub struct Invoice { total: u64 }

impl Invoice {
    pub fn new(total: u64) -> Self { Self { total } }
    pub fn total(&self) -> u64 { self.total }
    pub(crate) fn audit(&self) {} // visible inside this crate only
}
  • Go. All .go files in one directory share a package and see each other's unexported names. Import cycles are a compile error, which forces a clean dependency direction.
  • Go. An internal/ directory can only be imported by code under its parent: Go's version of package-private.
  • Rust. A crate is one compilation unit (a library or a binary); modules live inside it. pub(crate) is the "internal" visibility.

Suggest an edit to this topic

Each language has one standard tool that installs packages and writes a manifest plus a lock file. Composer pulls from Packagist, Go fetches modules straight from their source repos (through a proxy), and Cargo pulls from crates.io.

PHP
// $ composer require guzzlehttp/guzzle
// $ composer require --dev pestphp/pest
// composer.json
{
    "require": {
        "php": "^8.4",
        "guzzlehttp/guzzle": "^8.6"
    },
    "require-dev": {
        "pestphp/pest": "^5.3"
    },
    "autoload": {
        "psr-4": { "App\\": "src/" }
    }
}
// composer.lock pins exact versions: commit it for apps
Go
// $ go mod init example.com/shop
// $ go get github.com/go-chi/chi/v5@latest
// $ go mod tidy      # add missing, drop unused
// go.mod
module example.com/shop

go 1.26

require github.com/go-chi/chi/v5 v5.5.0

require golang.org/x/sync v0.19.0 // indirect

// go.sum holds checksums: commit it.
// Modules are cached in $GOPATH/pkg/mod, no vendor/ by default.
// Dev tools: go get -tool <pkg>, then go tool <name>
Rust
# $ cargo new shop
# $ cargo add serde --features derive
# $ cargo add tokio --features full
# $ cargo add --dev pretty_assertions
# Cargo.toml
[package]
name = "shop"
version = "0.1.0"
edition = "2024"

[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

[dev-dependencies]
pretty_assertions = "1"

# Cargo.lock pins exact versions: commit it for apps.
  • Go. Go uses minimal version selection: it picks the oldest version that satisfies every requirement, not the newest. Major versions 2+ change the import path (/v5).
  • Rust. "1" in Cargo means ^1 like Composer's caret. Cargo features switch optional parts of a crate on, which keeps compile times and binaries small.
  • Tip. composer outdated ≈ go list -m -u all ≈ cargo update --dry-run (or the cargo-outdated plugin).

Suggest an edit to this topic

Generics

PHP has generics only in docblocks, checked by PHPStan or Psalm and ignored at runtime. Go and Rust check type parameters in the compiler; Rust adds trait bounds that say what a type must be able to do.

PHP
<?php
/**
 * @template T
 */
final class Collection
{
    /** @param list<T> $items */
    public function __construct(private array $items) {}

    /** @return T|null */
    public function first(): mixed
    {
        return $this->items[0] ?? null;
    }
}

/** @var Collection<User> $users */
$users = new Collection([new User('ada@example.com')]);
$first = $users->first(); // PHPStan knows: User|null
// At runtime PHP does not check T at all.
Go
type Number interface {
    ~int | ~int64 | ~float64 // type-set constraint
}

func Sum[T Number](xs []T) T {
    var total T
    for _, x := range xs {
        total += x
    }
    return total
}

type Stack[T any] struct{ items []T }

func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }

func (s *Stack[T]) Pop() (T, bool) {
    var zero T
    if len(s.items) == 0 {
        return zero, false
    }
    v := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return v, true
}

// Sum([]float64{1.5, 2.5}) == 4;  s := &Stack[string]{}
RustRun ↗
use std::fmt::Display;
use std::iter::Sum;

fn total<T: Sum<T> + Copy>(xs: &[T]) -> T {
    xs.iter().copied().sum()
}

fn print_all<T>(items: &[T])
where
    T: Display, // trait bound: T must be printable
{
    for i in items { println!("{i}"); }
}

struct Stack<T> { items: Vec<T> }

impl<T> Stack<T> {
    fn new() -> Self { Self { items: Vec::new() } }
    fn push(&mut self, v: T) { self.items.push(v); }
    fn pop(&mut self) -> Option<T> { self.items.pop() }
}

fn main() {
    println!("{}", total(&[1.5, 2.5])); // 4
    print_all(&["a", "b"]);
    let mut s = Stack::new();
    s.push("a");
    let _ = s.pop();
}
  • PHP. Run PHPStan at level 6+ (or Larastan in Laravel) to get real value from @template. It is the closest PHP gets to compiler-checked generics.
  • Go. Constraints are interfaces listing a type set. any is an alias for interface{}, roughly PHP's mixed. Interface methods cannot declare their own type parameters.
  • Tip. New in Go 1.27: generic methods. A method may declare its own type parameters, e.g. func (s *Stack[T]) Map[U any](f func(T) U) []U; before 1.27 that had to be a package-level function.
  • Rust. Generics are monomorphised (a copy per concrete type), so they cost nothing at runtime. Bounds (T: Display) unlock what you may call on T.

Suggest an edit to this topic

PHP has array_map/array_filter and Laravel's fluent collect(). Go prefers plain loops plus helpers from the slices and maps packages. Rust iterator chains read almost exactly like Laravel collections and compile to tight loops.

PHP
<?php
$orders = [
    ['id' => 1, 'total' => 120, 'paid' => true],
    ['id' => 2, 'total' => 80,  'paid' => false],
    ['id' => 3, 'total' => 200, 'paid' => true],
];

$paidTotal = array_sum(array_map(
    fn ($o) => $o['total'],
    array_filter($orders, fn ($o) => $o['paid']),
)); // 320

// Laravel collections read left to right:
$paidTotal = collect($orders)->where('paid', true)->sum('total');
$ids = collect($orders)->pluck('id')->all(); // [1, 2, 3]
$hasBig = collect($orders)->contains(fn ($o) => $o['total'] > 150);
Go
type Order struct {
    ID, Total int
    Paid      bool
}

orders := []Order{{1, 120, true}, {2, 80, false}, {3, 200, true}}

// Idiomatic Go: a plain loop
paidTotal := 0
ids := make([]int, 0, len(orders))
for _, o := range orders {
    if o.Paid {
        paidTotal += o.Total
    }
    ids = append(ids, o.ID)
}

// Helpers from the std slices package
hasBig := slices.ContainsFunc(orders, func(o Order) bool { return o.Total > 150 })
firstUnpaid := slices.IndexFunc(orders, func(o Order) bool { return !o.Paid })
fmt.Println(paidTotal, ids, hasBig, firstUnpaid) // 320 [1 2 3] true 1
RustRun ↗
struct Order { id: u32, total: u32, paid: bool }

fn main() {
    let orders = vec![
        Order { id: 1, total: 120, paid: true },
        Order { id: 2, total: 80, paid: false },
        Order { id: 3, total: 200, paid: true },
    ];

    let paid_total: u32 = orders.iter()
        .filter(|o| o.paid)
        .map(|o| o.total)
        .sum(); // 320; nothing runs until .sum()

    let ids: Vec<u32> = orders.iter().map(|o| o.id).collect();
    let has_big = orders.iter().any(|o| o.total > 150);
    let (paid, unpaid): (Vec<&Order>, Vec<&Order>) =
        orders.iter().partition(|o| o.paid);

    println!("{paid_total} {ids:?} {has_big} {} {}", paid.len(), unpaid.len());
}
  • Rust. iter() borrows items, into_iter() consumes the collection, iter_mut() lets you change items in place. collect() needs a target type, given by annotation or turbofish ::<Vec<_>>.
  • Go. No map/filter in the standard library. Since Go 1.23 range-over-func iterators exist (slices.Collect, maps.Keys), but a for loop is still the house style.
  • Tip. New in PHP 8.5: the pipe operator |> chains plain functions left to right. With PHP 8.6 partial application it reads like a collection: $orders |> array_filter(?, fn ($o) => $o['paid']) |> array_column(?, 'total') |> array_sum(...).
  • Watch out. PHP's array_filter keeps the original keys, so [0 => .., 2 => ..] surprises people. Go slices and Rust Vecs never have gaps.

Suggest an edit to this topic

PHP turns arrays and objects into JSON with json_encode. Go maps JSON onto structs using field tags. Rust uses serde, which derives the conversion code at compile time and rejects data that does not match the type.

<?php
final class User implements JsonSerializable
{
    public function __construct(
        public int $id,
        public string $email,
        public ?string $nickname = null,
    ) {}

    public function jsonSerialize(): array
    {
        return array_filter(get_object_vars($this), fn ($v) => $v !== null);
    }
}

echo json_encode(new User(1, 'ada@example.com'));
// {"id":1,"email":"ada@example.com"}

$data = json_decode('{"id":2,"email":"bob@example.com"}', true, flags: JSON_THROW_ON_ERROR);
echo $data['email'];
Go
type User struct {
    ID       int    `json:"id"`
    Email    string `json:"email"`
    Nickname string `json:"nickname,omitempty"` // skip if empty
    Password string `json:"-"`                  // never encoded
}

func main() {
    b, err := json.Marshal(User{ID: 1, Email: "ada@example.com"})
    if err != nil { log.Fatal(err) }
    fmt.Println(string(b)) // {"id":1,"email":"ada@example.com"}

    var u User
    err = json.Unmarshal([]byte(`{"id":2,"email":"bob@example.com"}`), &u)
    if err != nil { log.Fatal(err) }
    fmt.Println(u.Email)

    var m map[string]any // unknown shape, like an assoc array
    _ = json.Unmarshal(b, &m)
}
RustRun ↗
// Cargo.toml: serde = { version = "1", features = ["derive"] }, serde_json = "1"
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct User {
    id: u32,
    email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    nickname: Option<String>,
    #[serde(skip)]
    password: String, // never (de)serialised
}

fn main() -> Result<(), serde_json::Error> {
    let u = User { id: 1, email: "ada@example.com".into(), nickname: None, password: String::new() };
    println!("{}", serde_json::to_string(&u)?); // {"id":1,"email":"ada@example.com"}

    let bob: User = serde_json::from_str(r#"{"id":2,"email":"bob@example.com"}"#)?;
    println!("{}", bob.email);

    let v: serde_json::Value = serde_json::from_str(r#"{"any":"shape"}"#)?;
    println!("{}", v["any"]); // untyped access
    Ok(())
}
  • Go. Only exported (Capitalised) fields are encoded. A lowercase field is silently skipped, a classic first-week bug.
  • Rust. A missing required field or wrong type is an Err, not a silent null. Option<T> fields may be absent. Use #[serde(rename_all = "camelCase")] to match JS-style keys.
  • PHP. json_decode returns null on bad input unless you pass JSON_THROW_ON_ERROR. Laravel API Resources play the role of the explicit response structs here.
  • Tip. New in Go 1.27: encoding/json/v2 joins the standard library with stricter defaults (it rejects invalid UTF-8 and duplicate keys), and encoding/json now runs on the v2 engine with unchanged behaviour.

Suggest an edit to this topic

Same three moves in each language: read a whole file, append to one, and stream a big file line by line. Go cleans up with defer; Rust closes the file automatically when it goes out of scope.

PHP
<?php
// Whole file at once
$config = file_get_contents('config.txt');
file_put_contents('out.txt', "hello\n", FILE_APPEND);

// Line by line (memory friendly)
$fh = fopen('access.log', 'r');
while (($line = fgets($fh)) !== false) {
    if (str_contains($line, 'ERROR')) {
        echo $line;
    }
}
fclose($fh);

// Laravel: Storage::disk('local')->get('config.txt');
Go
func main() {
    data, err := os.ReadFile("config.txt") // []byte
    if err != nil { log.Fatal(err) }
    fmt.Print(string(data))

    out, err := os.OpenFile("out.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
    if err != nil { log.Fatal(err) }
    defer out.Close() // runs when main returns
    out.WriteString("hello\n")

    in, err := os.Open("access.log")
    if err != nil { log.Fatal(err) }
    defer in.Close()

    sc := bufio.NewScanner(in)
    for sc.Scan() {
        if strings.Contains(sc.Text(), "ERROR") {
            fmt.Println(sc.Text())
        }
    }
    if err := sc.Err(); err != nil { log.Fatal(err) }
}
Rust
use std::fs::{self, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};

fn main() -> io::Result<()> {
    let config = fs::read_to_string("config.txt")?;
    print!("{config}");

    let mut out = OpenOptions::new().append(true).create(true).open("out.txt")?;
    writeln!(out, "hello")?;

    let file = fs::File::open("access.log")?;
    for line in BufReader::new(file).lines() {
        let line = line?;
        if line.contains("ERROR") {
            println!("{line}");
        }
    }
    Ok(()) // files close when they go out of scope
}
  • Go. defer is Go's finally for cleanup; deferred calls run in reverse order when the function returns.
  • Rust. read_to_string fails on invalid UTF-8; use fs::read for raw bytes. Cleanup happens through Drop (RAII), so there is no fclose.
  • Tip. New in PHP 8.6: a stream context with 'error_mode' => StreamErrorMode::Exception makes file_get_contents() and friends throw StreamException instead of returning false with a warning, closer to Go's err and Rust's Result.
  • Tip. In all three, read large logs line by line with a buffered reader instead of loading the whole file into memory.

Suggest an edit to this topic

Unit testing

PHP needs PHPUnit or Pest from Composer. Go and Rust ship a test runner in the toolchain: go test finds _test.go files, and cargo test runs #[test] functions that usually sit next to the code they test.

PHP
<?php
// tests/Unit/SlugTest.php  — run: ./vendor/bin/pest
function slug(string $s): string
{
    return strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $s), '-'));
}

it('slugifies titles', function (string $in, string $out) {
    expect(slug($in))->toBe($out);
})->with([
    ['Hello World', 'hello-world'],
    ['  PHP & Go!  ', 'php-go'],
]);

// PHPUnit style:
// $this->assertSame('hello-world', slug('Hello World'));
Go
// slug_test.go (same package)  — run: go test ./...
package text

import "testing"

func TestSlug(t *testing.T) {
    tests := []struct {
        name, in, want string
    }{
        {"spaces", "Hello World", "hello-world"},
        {"symbols", "  PHP & Go!  ", "php-go"},
    }
    for _, tt := range tests { // table-driven test
        t.Run(tt.name, func(t *testing.T) {
            if got := Slug(tt.in); got != tt.want {
                t.Errorf("Slug(%q) = %q, want %q", tt.in, got, tt.want)
            }
        })
    }
}
Rust
// src/text.rs  — run: cargo test
pub fn slug(s: &str) -> String {
    s.split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|p| !p.is_empty())
        .map(|p| p.to_lowercase())
        .collect::<Vec<_>>()
        .join("-")
}

#[cfg(test)] // compiled only for cargo test
mod tests {
    use super::*;

    #[test]
    fn slugifies_titles() {
        assert_eq!(slug("Hello World"), "hello-world");
        assert_eq!(slug("  PHP & Go!  "), "php-go");
    }

    #[test]
    #[should_panic]
    fn panics_are_testable() { panic!("expected"); }
}
  • Go. There is no assertion library in std; if got != want { t.Errorf(...) } is idiomatic. testify is the popular add-on. Benchmarks are func BenchmarkX(b *testing.B) with a for b.Loop() { ... } body.
  • Rust. Unit tests live in the same file; integration tests go in tests/; code examples in /// doc comments run as doc tests too.
  • Tip. Useful flags: go test -race -cover ./... and cargo test -- --nocapture (show println! output).

Suggest an edit to this topic

PHP has DateTimeImmutable built in and Laravel adds Carbon. Go's time package formats with a reference date instead of Y-m-d letters. Rust's standard library only has durations and instants; calendar dates come from chrono or jiff.

<?php
$tz = new DateTimeZone('America/Toronto');
$now = new DateTimeImmutable('now', $tz);

$due = $now->modify('+14 days');
echo $due->format('Y-m-d H:i');           // 2026-12-19 09:30

$xmas = DateTimeImmutable::createFromFormat('Y-m-d', '2026-12-25', $tz);
$days = $now->diff($xmas)->days;

// Laravel / Carbon:
// now()->addDays(14)->toDateString();
// Carbon::parse('2026-12-25')->diffForHumans();
Go
func main() {
    loc, err := time.LoadLocation("America/Toronto")
    if err != nil { log.Fatal(err) }
    now := time.Now().In(loc)

    due := now.AddDate(0, 0, 14)
    fmt.Println(due.Format("2006-01-02 15:04")) // reference-date layout

    xmas, err := time.ParseInLocation("2006-01-02", "2026-12-25", loc)
    if err != nil { log.Fatal(err) }
    days := int(xmas.Sub(now).Hours() / 24)

    timeout := 90 * time.Second // a time.Duration
    fmt.Println(days, timeout)  // ... 1m30s
}
Rust
// Cargo.toml: chrono = "0.4", chrono-tz = "0.10"
use chrono::{Duration, NaiveDate, Utc};
use chrono_tz::America::Toronto;

fn main() {
    let now = Utc::now().with_timezone(&Toronto);

    let due = now + Duration::days(14);
    println!("{}", due.format("%Y-%m-%d %H:%M"));

    let xmas = NaiveDate::parse_from_str("2026-12-25", "%Y-%m-%d").unwrap();
    let days = (xmas - now.date_naive()).num_days();

    let timeout = std::time::Duration::from_secs(90); // std: durations only
    println!("{days} {timeout:?}"); // ... 90s
}
  • Go. Layouts are written with the reference time Mon Jan 2 15:04:05 MST 2006 (1-2-3-4-5-6-7). Y-m-d becomes 2006-01-02, H:i becomes 15:04.
  • Rust. chrono is the most used crate; jiff is a newer option with stronger time-zone and DST handling. Both treat dates as values, like DateTimeImmutable.
  • Watch out. Store UTC in the database and convert at the edges, in all three. Go's time.Time and Rust's chrono types are values, so there is no mutable-DateTime trap.
  • Tip. New in PHP 8.6: a built-in \Time\Duration value (Duration::fromSeconds(90)), PHP's counterpart to Go's time.Duration and Rust's std::time::Duration.

Suggest an edit to this topic

Advanced

Memory, concurrency, the network and the build. This is where Go and Rust stop looking like "PHP with types" and work in a different way, because both run as long-lived processes rather than a fresh process per request.

Memory model

PHP counts references and throws everything away at the end of the request. Go uses a tracing garbage collector in a long-lived process. Rust has no collector: every value has one owner and is freed when that owner goes out of scope.

<?php
function build(): array {
    $user = new User("Ada");   // refcount = 1
    $copy = $user;             // same object, refcount = 2
    unset($copy);              // refcount = 1
    $rows = range(1, 1_000_000);
    return $rows;              // $user freed here (refcount 0)
}

// Cycles ($a->b = $b; $b->a = $a) need the cycle collector:
gc_collect_cycles();
echo memory_get_peak_usage(true);
// End of request: PHP-FPM throws everything away anyway.
Go
type User struct{ Name string }

func newUser(name string) *User {
	u := User{Name: name} // escapes to the heap: pointer outlives the call
	return &u
}

func sum() int {
	nums := [3]int{1, 2, 3} // stays on the stack, no GC work
	return nums[0] + nums[1] + nums[2]
}

// go build -gcflags=-m      prints escape-analysis decisions
// GOGC=200 GOMEMLIMIT=512MiB tune the collector at runtime
RustRun ↗
struct User { name: String }

impl Drop for User {                 // like __destruct, but deterministic
    fn drop(&mut self) { println!("freeing {}", self.name); }
}

fn main() {
    let a = User { name: "Ada".into() };
    let b = a;                       // ownership MOVES to b
    // println!("{}", a.name);       // compile error: value moved
    {
        let _tmp = User { name: "Tmp".into() };
    }                                // "freeing Tmp": end of scope
    println!("{}", b.name);
}                                    // "freeing Ada": no GC, no refcount
  • PHP. Memory leaks rarely hurt in PHP-FPM because each request starts clean. They matter in Octane, queue workers and long-running daemons, which behave like Go and Rust processes.
  • Go. Returning a pointer to a local variable is fine in Go: the compiler moves it to the heap. Fewer heap allocations means less GC work, so -benchmem allocation counts are worth watching.
  • Rust. Assignment moves heap data such as String and Vec. Types that are Copy (integers, bool, char) are copied instead. Use .clone() when you really want a second copy.
  • Go. The Green Tea garbage collector is on by default; it cuts GC overhead for programs that allocate many small objects.

Suggest an edit to this topic

PHP passes arrays by value (copy-on-write) and objects by handle, with & as an escape hatch. Go makes you choose between a value and a pointer. Rust lends values out as & (shared, read-only) or &mut (exclusive) borrows, and the compiler checks every one.

PHP
<?php
function addTag(array $tags): array { $tags[] = "new"; return $tags; } // copy-on-write
function addTagRef(array &$tags): void { $tags[] = "new"; }            // by reference

$tags = ["php"];
$copy = addTag($tags);    // $tags unchanged
addTagRef($tags);         // $tags mutated in place

function renameUser(User $u): void { $u->name = "Grace"; }
$user = new User("Ada");
renameUser($user);        // objects are handles: caller sees "Grace"
Go
type User struct{ Name string }

func renameCopy(u User) { u.Name = "Copy" }  // value: mutates a copy
func rename(u *User)    { u.Name = "Grace" } // pointer: mutates caller's

// Pointer receiver: the method can change the struct
func (u *User) SetName(n string) { u.Name = n }

func main() {
	u := User{Name: "Ada"}
	renameCopy(u)      // u.Name is still "Ada"
	rename(&u)         // u.Name is now "Grace"
	u.SetName("Linus") // Go takes &u for you
	fmt.Println(u.Name)
}
RustRun ↗
fn len(s: &String) -> usize { s.len() }   // shared borrow: read-only
fn shout(s: &mut String) { s.push('!'); } // exclusive borrow: may mutate

// Lifetime 'a: the returned &str may not outlive either input
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let mut name = String::from("Ada");
    let n = len(&name);     // any number of & borrows at once...
    shout(&mut name);       // ...or exactly one &mut, never both
    println!("{name} {n} {}", longest("php", "rust"));
}
  • Go. Rule of thumb: use a pointer receiver if the method mutates the struct or the struct is large. Keep all methods on one type consistent.
  • Rust. The borrow rule in one line: many readers or one writer, never both at the same time. It is what rules out data races at compile time.
  • Rust. You rarely write lifetimes. The compiler infers them; you annotate when a function returns a reference and has several reference inputs (and no &self), or when a struct holds a reference.
  • Tip. In function signatures, accept &str instead of &String and &[T] instead of &Vec<T>. They take strictly more inputs.

Suggest an edit to this topic

In PHP every object variable is already a shared handle. In Go, pointers and slices share data and the GC cleans up. Rust makes sharing explicit with wrapper types: Box (heap), Rc/Arc (shared ownership) and RefCell/Mutex (mutation through a shared handle).

PHP
<?php
$a = new Cart();
$b = $a;               // same object (handle copy), like Rc
$c = clone $a;         // explicit shallow copy
$b->add('book');       // $a sees it too

// Weak reference: cache without keeping the object alive
$totals = new WeakMap();
$totals[$a] = $a->total();
unset($a, $b);         // entry disappears from $totals
echo count($totals);   // 0
Go
type Node struct {
	Val  int
	Next *Node // pointer: optional, shared, recursive
}

func main() {
	list := &Node{1, &Node{2, nil}}
	shared := list  // both point at the same Node
	shared.Val = 10 // list.Val is 10 too; GC frees it later

	nums := []int{1, 2, 3, 4}
	head := nums[:2] // shares the backing array with nums
	head[0] = 99     // nums[0] is now 99
	fmt.Println(list.Val, nums[0])
}
RustRun ↗
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};

#[derive(Debug)]
enum List { Cons(i32, Box<List>), Nil } // Box: heap + recursive type

fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));

    let cart = Rc::new(RefCell::new(vec![10, 20])); // shared, one thread
    let alias = Rc::clone(&cart);                   // refcount 2
    alias.borrow_mut().push(30);                    // checked at runtime
    println!("{:?} rc={}", cart.borrow(), Rc::strong_count(&cart));

    let hits = Arc::new(Mutex::new(0));             // shared across threads
    *hits.lock().unwrap() += 1;
    println!("{list:?} {}", hits.lock().unwrap());
}
  • Rust. Pick by need: Box<T> for one owner on the heap, Rc<T> for many owners on one thread, Arc<T> for many owners across threads. Add RefCell or Mutex inside only if you must mutate.
  • Watch out. Rc cycles leak: Rust has no cycle collector like the one behind PHP’s gc_collect_cycles(). Use Weak<T> for back-references such as parent pointers, similar to PHP WeakReference.
  • Go. Sub-slices alias the original array until append grows past capacity and copies. Use slices.Clone when you need an independent copy.

Suggest an edit to this topic

PHP gets parallelism from many processes: FPM workers, pcntl_fork or queue workers. Go starts thousands of cheap goroutines that talk over channels. Rust uses OS threads with channels, and the compiler refuses to build code that has a data race.

PHP
<?php
// PHP shares nothing between processes. Fork for parallel work...
$pids = [];
foreach (['a.csv', 'b.csv', 'c.csv'] as $file) {
    $pid = pcntl_fork();
    if ($pid === 0) { importCsv($file); exit(0); } // child
    $pids[] = $pid;
}
foreach ($pids as $pid) {
    pcntl_waitpid($pid, $status);
}

// ...or, far more common in Laravel, fan out to queue workers:
// Bus::batch(array_map(fn ($f) => new ImportCsv($f), $files))->dispatch();
Go
func main() {
	files := []string{"a.csv", "b.csv", "c.csv"}
	results := make(chan string, len(files))
	var wg sync.WaitGroup

	for _, f := range files {
		wg.Go(func() { // goroutine: starts with a ~2 KB stack
			results <- importCSV(f) // send on the channel
		})
	}
	wg.Wait()
	close(results)
	for r := range results { // receive until closed
		fmt.Println(r)
	}
}
RustRun ↗
use std::sync::mpsc;
use std::thread;

fn main() {
    let files = ["a.csv", "b.csv", "c.csv"];
    let (tx, rx) = mpsc::channel();

    thread::scope(|s| {                // scoped threads may borrow `files`
        for f in &files {
            let tx = tx.clone();
            s.spawn(move || tx.send(format!("imported {f}")).unwrap());
        }
    });                                // every thread is joined here
    drop(tx);                          // close the channel

    for msg in rx {
        println!("{msg}");
    }
}
  • Go. "Do not communicate by sharing memory; share memory by communicating." Channels carry ownership of data between goroutines. Run tests with go test -race to catch the races they do not cover.
  • Go. Each loop iteration has its own f, so capturing it in a goroutine is safe. wg.Go starts the goroutine and does the Add/Done bookkeeping for you.
  • Rust. The Send and Sync marker traits decide what may cross threads. Trying to move an Rc into thread::spawn is a compile error, not a production bug.
  • Tip. For CPU-bound parallel loops in Rust, the rayon crate turns .iter() into .par_iter() with no other changes.

Suggest an edit to this topic

Async I/O

PHP 8.1 Fibers let libraries such as Amp and ReactPHP run many I/O calls on one thread. Go has no async/await: goroutines block cheaply and the runtime handles the waiting. Rust has async/await built into the language, but you choose a runtime such as Tokio to run it.

PHP
<?php
// composer require amphp/http-client (Fibers under the hood)
use Amp\Http\Client\{HttpClientBuilder, Request};
use function Amp\async;
use function Amp\Future\await;

$http = HttpClientBuilder::buildDefault();
$urls = ['https://a.test', 'https://b.test'];

$futures = array_map(
    fn ($url) => async(fn () => $http->request(new Request($url))->getBody()->buffer()),
    $urls,
);
$bodies = await($futures);   // both requests run concurrently

// Laravel: Http::pool(fn (Pool $p) => [$p->get($urls[0]), $p->get($urls[1])]);
Go
// No async/await: block inside goroutines; the runtime parks them.
func fetchAll(urls []string) []string {
	bodies := make([]string, len(urls))
	var wg sync.WaitGroup
	for i, url := range urls {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := http.Get(url)
			if err != nil {
				return
			}
			defer resp.Body.Close()
			b, _ := io.ReadAll(resp.Body)
			bodies[i] = string(b) // each goroutine owns one index
		}()
	}
	wg.Wait()
	return bodies
}
RustRun ↗
// tokio = { version = "1", features = ["full"] }, reqwest = "0.12"
async fn fetch(url: &str) -> reqwest::Result<String> {
    reqwest::get(url).await?.text().await
}

#[tokio::main]
async fn main() {
    // join!: run both futures concurrently and wait for both
    let (a, b) = tokio::join!(fetch("https://a.test"), fetch("https://b.test"));
    println!("{} {}", a.is_ok(), b.is_ok());

    // spawn: a background task, like `go func()`
    let task = tokio::spawn(async { fetch("https://c.test").await.map(|s| s.len()) });
    let len = task.await.unwrap(); // JoinHandle -> Result
    println!("{len:?}");
}
  • Rust. Futures are lazy: nothing happens until you .await, join! or spawn them. Calling an async fn on its own does nothing, which surprises people coming from JavaScript.
  • Watch out. Never block inside async Rust (std::thread::sleep, heavy CPU loops, sync file I/O). It stalls the whole worker thread. Use tokio::time::sleep or tokio::task::spawn_blocking.
  • Go. Go avoids "function colouring": any function can do I/O, and any call can be made concurrent with go. The cost is that cancellation has to be passed by hand through context.Context (see next topic).
  • Laravel. Http::pool() and Concurrency::run() (Laravel 11+) cover most fan-out needs without leaving Laravel.

Suggest an edit to this topic

PHP requests share no memory, so locks live in Redis or on disk. Go protects shared memory with sync.Mutex, sync.Once and sync/atomic. Rust wraps the data itself in Mutex<T> inside an Arc, so you cannot reach the data without taking the lock.

PHP
<?php
use Illuminate\Support\Facades\Cache;

// Distributed lock (Redis/DB): one worker at a time across servers
Cache::lock('invoice:42', 10)->block(5, function () {
    Invoice::find(42)->finalize();
});

// Plain PHP: an exclusive file lock on one machine
$fp = fopen('/tmp/report.lock', 'c');
if (flock($fp, LOCK_EX | LOCK_NB)) {
    buildReport();
    flock($fp, LOCK_UN);
}
Go
type Counter struct {
	mu   sync.Mutex
	hits map[string]int
}

func (c *Counter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.hits[key]++
}

var (
	once  sync.Once
	cfg   *Config
	total atomic.Int64 // lock-free counter
)

func GetConfig() *Config {
	once.Do(func() { cfg = loadConfig() }) // runs exactly once
	total.Add(1)
	return cfg
}
RustRun ↗
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;

static TOTAL: AtomicU64 = AtomicU64::new(0);
static CONFIG: OnceLock<String> = OnceLock::new();

fn main() {
    let hits = Arc::new(Mutex::new(HashMap::<String, u32>::new()));
    let handles: Vec<_> = (0..4).map(|_| {
        let hits = Arc::clone(&hits);
        thread::spawn(move || {
            *hits.lock().unwrap().entry("home".into()).or_default() += 1;
            TOTAL.fetch_add(1, Ordering::Relaxed);
        })
    }).collect();
    for h in handles { h.join().unwrap(); }

    let cfg = CONFIG.get_or_init(|| "loaded once".to_string());
    println!("{:?} {} {cfg}", hits.lock().unwrap(), TOTAL.load(Ordering::Relaxed));
}
  • Go. A plain Go map is not safe for concurrent writes; the runtime crashes with "concurrent map writes". Guard it with a mutex, or use sync.Map for read-heavy caches.
  • Rust. The lock is released when the MutexGuard is dropped, usually at the end of the statement or block. There is no Unlock() to forget.
  • Tip. Your Go or Rust service still needs Redis locks when it runs on several servers. In-process mutexes only protect one process, just as flock only protects one machine.

Suggest an edit to this topic

PHP has a script-wide set_time_limit and per-call client timeouts. Go passes a context.Context down every call chain so work can be cancelled or given a deadline. In Rust, dropping a future cancels it, and tokio::time::timeout, select! and CancellationToken give you control over when.

PHP
<?php
set_time_limit(30);                    // whole script dies after 30 s

$rates = Http::timeout(5)              // Laravel HTTP client
    ->connectTimeout(2)
    ->retry(3, 200)                    // 3 tries, 200 ms apart
    ->get('https://api.example.com/rates')
    ->json();

// Guzzle directly
$client = new GuzzleHttp\Client(['timeout' => 5.0]);

// Cancelling work running elsewhere = a flag the job checks:
// if (Cache::get("import:{$id}:cancelled")) return;
Go
func handler(w http.ResponseWriter, r *http.Request) {
	// r.Context() is cancelled if the client disconnects
	ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
	defer cancel()

	req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.example.com/rates", nil)
	resp, err := http.DefaultClient.Do(req)
	if errors.Is(err, context.DeadlineExceeded) {
		http.Error(w, "upstream too slow", http.StatusGatewayTimeout)
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()
	io.Copy(w, resp.Body)
}

// Workers watch ctx.Done() in a select:
// select { case <-ctx.Done(): return ctx.Err(); case job := <-jobs: ... }
RustRun ↗
use std::time::Duration;
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;

async fn slow_call() -> u32 { sleep(Duration::from_secs(5)).await; 42 }

#[tokio::main]
async fn main() {
    match timeout(Duration::from_secs(2), slow_call()).await {
        Ok(v) => println!("got {v}"),
        Err(_) => println!("timed out"),  // the future is dropped = cancelled
    }

    let token = CancellationToken::new();
    let child = token.clone();
    let worker = tokio::spawn(async move {
        tokio::select! {
            _ = child.cancelled() => "stopped",
            _ = sleep(Duration::from_secs(60)) => "finished",
        }
    });
    token.cancel();
    println!("{}", worker.await.unwrap()); // "stopped"
}
  • Go. Convention: ctx context.Context is the first parameter of any function that does I/O. Always defer cancel() to release the timer.
  • Rust. Cancellation happens at .await points: a dropped future simply never resumes. Make sure state stays consistent if your code stops between two awaits.
  • Tip. Set a timeout on every outbound HTTP call in all three languages. Go’s http.DefaultClient and Rust’s reqwest::get have no overall timeout by default.

Suggest an edit to this topic

In PHP the web server (FPM, FrankenPHP or php -S) starts your script once per request. In Go and Rust your program is the server: it binds a port and lives for days. Go’s standard library has had method and path-parameter routing since 1.22. In Rust, axum is the usual choice.

PHP
<?php
// public/index.php — run: php -S localhost:8000 public/index.php
$method = $_SERVER['REQUEST_METHOD'];
$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
header('Content-Type: application/json');

if ($method === 'GET' && preg_match('#^/users/(\d+)$#', $path, $m)) {
    echo json_encode(['id' => (int) $m[1], 'name' => 'Ada']);
    return;
}

http_response_code(404);
echo json_encode(['error' => 'Not found']);
Go
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
		id, err := strconv.Atoi(r.PathValue("id"))
		if err != nil {
			http.Error(w, "bad id", http.StatusBadRequest)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]any{"id": id, "name": "Ada"})
	})
	log.Println("listening on :8000")
	log.Fatal(http.ListenAndServe(":8000", mux)) // one long-running process
}
Rust
// axum = "0.8", tokio = { version = "1", features = ["full"] }, serde_json = "1"
use axum::{Json, Router, extract::Path, routing::get};
use serde_json::{Value, json};

async fn show_user(Path(id): Path<u64>) -> Json<Value> {
    Json(json!({ "id": id, "name": "Ada" }))  // bad id -> automatic 400
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(show_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
  • Go. Every request runs in its own goroutine. Anything global (maps, caches, counters) is shared between requests, which never happens in PHP-FPM.
  • Rust. Axum handlers are plain async functions whose arguments are extractors (Path, Query, Json, State). If extraction fails, axum returns the 4xx for you.
  • Tip. The PHP version is what Laravel’s router, middleware and request objects replace. Compare this topic with Routing and Request on the Frameworks page.

Suggest an edit to this topic

PDO, database/sql and sqlx all play the same part: one connection API, prepared statements and transactions. The difference is how rows come back. PHP gives you arrays, Go makes you Scan columns into variables, and Rust maps rows onto a struct, optionally checking the SQL at compile time.

PHP
<?php
$pdo = new PDO('pgsql:host=localhost;dbname=app', 'app', 'secret', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = :id');
$stmt->execute(['id' => 42]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);   // array|false

$pdo->beginTransaction();
$pdo->prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?')
    ->execute([100, 1]);
$pdo->commit();
Go
import (
	"database/sql"
	_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)

type User struct {
	ID    int64
	Name  string
	Email string
}

func findUser(ctx context.Context, db *sql.DB, id int64) (User, error) {
	var u User
	err := db.QueryRowContext(ctx,
		"SELECT id, name, email FROM users WHERE id = $1", id,
	).Scan(&u.ID, &u.Name, &u.Email) // columns by position
	if errors.Is(err, sql.ErrNoRows) {
		return u, fmt.Errorf("user %d not found", id)
	}
	return u, err
}
// db, err := sql.Open("pgx", os.Getenv("DATABASE_URL")) — open ONCE, share it
Rust
// sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
use sqlx::{FromRow, PgPool};

#[derive(Debug, FromRow)]
struct User { id: i64, name: String, email: String }

async fn find_user(pool: &PgPool, id: i64) -> Result<Option<User>, sqlx::Error> {
    sqlx::query_as::<_, User>("SELECT id, name, email FROM users WHERE id = $1")
        .bind(id)
        .fetch_optional(pool)    // Ok(None) instead of an error
        .await
}

// query_as! checks the SQL against a real database at compile time:
// let u = sqlx::query_as!(User, "SELECT id, name, email FROM users WHERE id = $1", id)
//     .fetch_one(&pool).await?;
  • Go. *sql.DB is a connection pool, safe for concurrent use. Create it once at startup and pass it around. Never open a connection per request as you would in PHP.
  • Go. Prefer struct-scanning helpers over hand-written Scan calls: sqlc generates typed code from SQL, and sqlx (Go) or pgx.CollectRows map columns by name.
  • Rust. query_as! needs DATABASE_URL at build time, or cargo sqlx prepare to save query metadata for offline builds in CI.
  • Tip. Postgres placeholders are $1, $2 in Go and Rust, not PDO’s ? or :name. MySQL drivers use ?.

Suggest an edit to this topic

PHP reads attributes through Reflection at runtime. Go has struct tags, the reflect package and code generation before the build (go generate). Rust does it at compile time: #[derive] and other macros write code for you, so there is no runtime cost.

<?php
#[Attribute(Attribute::TARGET_PROPERTY)]
final class Column {
    public function __construct(public string $name) {}
}

final class User {
    #[Column('user_name')]
    public string $name = 'Ada';
}

foreach ((new ReflectionClass(User::class))->getProperties() as $prop) {
    foreach ($prop->getAttributes(Column::class) as $attr) {
        echo $prop->getName(), ' -> ', $attr->newInstance()->name, PHP_EOL;
    }
}
// name -> user_name   (resolved at runtime)
Go
type User struct {
	Name string `json:"name" db:"user_name"`
}

func columns(v any) {
	t := reflect.TypeOf(v)
	for f := range t.Fields() { // iterator over the struct's fields
		fmt.Println(f.Name, "->", f.Tag.Get("db")) // Name -> user_name
	}
}

// Code generation: `go generate` runs this before you build

//go:generate stringer -type=Status
type Status int

const (
	Draft Status = iota
	Published
)
RustRun ↗
// serde = { version = "1", features = ["derive"] }
#[derive(Debug, Clone, PartialEq, serde::Serialize)] // impls written for you
struct User {
    #[serde(rename = "user_name")]   // read by the derive macro
    name: String,
}

// macro_rules!: pattern-matching on syntax
macro_rules! hashmap {
    ($($k:expr => $v:expr),* $(,)?) => {{
        let mut m = std::collections::HashMap::new();
        $( m.insert($k, $v); )*
        m
    }};
}

fn main() {
    let roles = hashmap! { "ada" => "admin", "grace" => "editor" };
    println!("{:?} {roles:?}", User { name: "Ada".into() });
}
  • Go. Struct tags are plain strings: a typo such as jsn:"name" compiles silently. go vet catches malformed tags, but not misspelled keys.
  • Rust. Procedural macros (#[derive(Serialize)], #[tokio::main], sqlx::query!) are small compiler plugins published as crates. Run cargo expand to see the code they generate.
  • Tip. Laravel’s magic (Eloquent attributes, facades, __call) is all runtime reflection. Go replaces it with explicit code or generators; Rust replaces it with macros and traits.

Suggest an edit to this topic

PHP hooks into the language through magic methods and built-in interfaces (__toString, Stringable, JsonSerializable, ArrayAccess). Go uses small standard interfaces you satisfy implicitly (fmt.Stringer, error, io.Reader). Rust uses standard traits (Display, From, TryFrom, Iterator).

<?php
final class Money implements Stringable, JsonSerializable {
    public function __construct(private int $cents, private string $cur = 'USD') {}

    public function __toString(): string {             // echo $m, (string) $m
        return sprintf('%s %.2f', $this->cur, $this->cents / 100);
    }

    public function jsonSerialize(): mixed { return ['cents' => $this->cents]; }

    public static function fromFloat(float $v): self { // named constructor ≈ From
        return new self((int) round($v * 100));
    }
}

echo Money::fromFloat(9.99);   // USD 9.99
Go
type Money struct {
	Cents int64
	Cur   string
}

// fmt.Stringer: used by Println, %v and %s
func (m Money) String() string {
	return fmt.Sprintf("%s %.2f", m.Cur, float64(m.Cents)/100)
}

// error is just an interface: any type with Error() string
type InsufficientFunds struct{ Need Money }

func (e InsufficientFunds) Error() string { return "need " + e.Need.String() }

// io.Writer: files, sockets, buffers, http.ResponseWriter...
func report(w io.Writer, m Money) { fmt.Fprintln(w, m) }
// report(os.Stdout, m); report(&bytes.Buffer{}, m)
RustRun ↗
use std::fmt;

struct Money { cents: i64 }

impl fmt::Display for Money {             // enables {} and .to_string()
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "USD {:.2}", self.cents as f64 / 100.0)
    }
}

impl From<i64> for Money {                // Money::from(999) and .into()
    fn from(cents: i64) -> Self { Money { cents } }
}

impl TryFrom<&str> for Money {            // fallible conversion
    type Error = std::num::ParseFloatError;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Ok(Money { cents: (s.parse::<f64>()? * 100.0).round() as i64 })
    }
}

fn main() {
    let a: Money = 999.into();
    let b = Money::try_from("12.50").unwrap();
    println!("{a} {b}");                  // USD 9.99 USD 12.50
}
  • Go. Learn io.Reader and io.Writer first. Files, HTTP bodies, gzip streams and buffers all implement them, so one function works with all of them.
  • Rust. Implement From<A> for B and you get Into<B> for A for free. The ? operator uses From to convert error types, which is why it is everywhere.
  • Tip. There is no __get/__call magic in Go or Rust. Dynamic property access becomes a method or a map, and that is deliberate.

Suggest an edit to this topic

For PHP, performance mostly means OPcache, fewer queries and a profiler such as Blackfire or SPX. Go has benchmarks and pprof built into its toolchain. Rust is fast only when built with --release, and it is measured with criterion and flamegraphs.

PHP
<?php
// 1. Measure first
$start = hrtime(true);
$total = array_sum(array_map(fn ($o) => $o->total, $orders));
printf("%.2f ms\n", (hrtime(true) - $start) / 1e6);

// 2. Profile: XDEBUG_MODE=profile, Blackfire (blackfire run php app.php) or SPX

// 3. Production php.ini
//    opcache.enable=1
//    opcache.validate_timestamps=0  ; no file stat per request
//    opcache.jit=tracing            ; helps CPU-bound code, rarely typical web I/O
Go
// sum_test.go — run: go test -bench=. -benchmem -cpuprofile=cpu.out
func BenchmarkSum(b *testing.B) {
	orders := make([]Order, 10_000)
	for b.Loop() { // older code: for i := 0; i < b.N; i++
		Sum(orders)
	}
}

// Inspect:   go tool pprof -http=:8080 cpu.out
// Live server: import _ "net/http/pprof" and open /debug/pprof/
Rust
// benches/sum.rs — [dev-dependencies] criterion = "0.5"
//                  [[bench]] name = "sum", harness = false
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;

fn bench_sum(c: &mut Criterion) {
    let orders: Vec<u64> = (0..10_000).collect();
    c.bench_function("sum", |b| b.iter(|| black_box(&orders).iter().sum::<u64>()));
}

criterion_group!(benches, bench_sum);
criterion_main!(benches);

// cargo bench
// cargo build --release         (debug builds are far slower)
// cargo flamegraph --bin app    (cargo install flamegraph)
  • PHP. In most Laravel apps the bottleneck is I/O: N+1 queries, missing indexes, slow APIs. Fix those (Telescope, Debugbar, Model::preventLazyLoading()) before you consider rewriting in another language.
  • Go. -benchmem reports allocations per operation. Cutting allocations (pre-sizing slices with make([]T, 0, n), reusing buffers) is the usual Go speed-up.
  • Rust. Never benchmark a debug build. cargo run --release can be an order of magnitude faster than cargo run.

Suggest an edit to this topic

All three can call C libraries. PHP does it through the FFI extension at runtime, Go through cgo, and Rust through extern blocks. Go and Rust also let you step outside the type system (unsafe.Pointer, unsafe { }), but they make it visible and opt-in.

PHP
<?php
// ffi.enable: "preload" by default (allowed in CLI); call C directly
$ffi = FFI::cdef(
    'size_t strlen(const char *s); int abs(int j);',
    'libc.so.6' // Linux; on macOS use 'libSystem.dylib'
);

echo $ffi->strlen('artisan'), PHP_EOL; // 7
echo $ffi->abs(-42), PHP_EOL;          // 42
package main

/*
#include <stdlib.h>
#include <string.h>
*/
import "C"

import (
	"fmt"
	"unsafe"
)

func main() {
	cs := C.CString("gopher") // allocated in C memory: free it yourself
	defer C.free(unsafe.Pointer(cs))
	fmt.Println(C.strlen(cs)) // 6

	n := 42
	p := unsafe.Pointer(&n) // bypasses the type system
	fmt.Println(*(*int)(p))
}
RustRun ↗
use std::ffi::{CString, c_char};

unsafe extern "C" {                  // 2024 edition: `unsafe extern`
    fn strlen(s: *const c_char) -> usize;
    safe fn abs(j: i32) -> i32;      // declared safe to call
}

fn main() {
    let s = CString::new("ferris").unwrap();
    let n = unsafe { strlen(s.as_ptr()) }; // you vouch the pointer is valid
    println!("{n} {}", abs(-42));

    let x = 7;
    let p = &x as *const i32;             // creating raw pointers is safe...
    println!("{}", unsafe { *p });        // ...dereferencing them is not
}
  • Go. cgo is not free: it slows builds, breaks easy cross-compiling, and each call costs far more than a Go call (Go 1.26 cut the base overhead by about 30%). Many teams set CGO_ENABLED=0 and use pure-Go libraries such as modernc.org/sqlite.
  • Rust. unsafe does not turn off the borrow checker. It unlocks five extra powers, such as dereferencing raw pointers and calling unsafe functions. Wrap them in a small, safe API.
  • Tip. Going the other way, you can write PHP extensions in Rust (ext-php-rs) or ship a Go/Rust binary that PHP calls over HTTP, a queue or proc_open. That is a gentle way to bring either language into a Laravel shop.

Suggest an edit to this topic

A PHP deploy ships source code, vendor/ and a runtime (PHP-FPM with nginx, or FrankenPHP). Go and Rust ship one compiled binary. Go cross-compiles with two environment variables. Rust needs a target installed, and musl gives a fully static binary.

PHP
# Dockerfile — FrankenPHP: PHP + Caddy in one image
FROM dunglas/frankenphp:1-php8.4
RUN install-php-extensions pdo_pgsql redis opcache intl
WORKDIR /app
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY . .
RUN composer install --no-dev --optimize-autoloader
ENV SERVER_NAME=:80

# On boot: php artisan optimize && php artisan migrate --force
# Classic setup: nginx + php-fpm. You ship source + vendor/.
Go
# Dockerfile — one static binary, no runtime needed
FROM golang:1 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /app ./cmd/server

FROM gcr.io/distroless/static-debian13
COPY --from=build /app /app
ENTRYPOINT ["/app"]

# Cross-compile on your Mac, no Docker needed:
#   GOOS=linux GOARCH=arm64 go build -o app-linux-arm64 ./cmd/server
Rust
# Dockerfile — multi-stage, release build
FROM rust:1-trixie AS build
WORKDIR /src
COPY . .
RUN cargo build --release --locked

# Same Debian release as the build stage, or the binary fails on glibc
FROM debian:trixie-slim
COPY --from=build /src/target/release/app /usr/local/bin/app
CMD ["app"]

# Fully static binary (no glibc):
#   rustup target add x86_64-unknown-linux-musl
#   cargo build --release --target x86_64-unknown-linux-musl
# Smaller/faster: [profile.release] lto = true, codegen-units = 1, strip = true
  • Go. A typical Go API image is 10–30 MB on distroless with no shell, compared with several hundred MB for a PHP image. It starts in milliseconds, which suits scale-to-zero platforms.
  • Rust. Rust release builds are slow, often minutes. Cache ~/.cargo/registry and target/ in CI, or use cargo-chef in Docker to cache the dependency layer.
  • Watch out. Do not run php artisan config:cache while building the image unless the build has the real environment. It bakes in whatever .env values it sees at build time.
  • Go. On Linux, GOMAXPROCS follows the container’s CPU limit (cgroup), so Go in Docker or Kubernetes needs no automaxprocs.

Suggest an edit to this topic