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.
Dynamic, optional type hints; declare(strict_types=1) per file
Static, inferred with :=; no implicit conversions
Static, inferred; strict, no implicit conversions
Runs as
Interpreted (OPcache + JIT), one process per request under FPM
Compiled to one native binary, long-running server
Compiled to one native binary, long-running server
Memory
Refcount + cycle GC, freed at end of request
Tracing garbage collector
Ownership and borrowing; no GC
Errors
Exceptions, try / catch
Errors are values: if err != nil
Result<T, E> and the ? operator
Null
null, ?->, ??
nil plus zero values
No null: Option<T>
Concurrency
Separate processes, queues, Fibers
Goroutines and channels
Threads, async/await with Tokio
Packages
Composer, Packagist
Go modules, go get
Cargo, crates.io
Learning curve
You already know it
A weekend to read, a month to be idiomatic
Weeks to fight the borrow checker, then it clicks
Releases
Yearly, each November
Every six months, February and August
Every six weeks
Level
Show
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.
// main.gopackage main
import"fmt"funcmain() {
fmt.Println("Hello, world!")
}
// go mod init example.com/hello// go run . compile + run (temp binary)// go build -o hello && ./hello
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 constantdefine('APP_ENV', 'local');
[$a, $b] = [1, 2]; // destructuring
Go
var name string = "Ada"// explicit type
city := "London"// := declares + infers// city = 42 // compile error: stringvar count int// zero value: 0
count++
constMaxUsers = 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 errorletmut count = 0; // opt in to mutation
count += 1;
let total: u32 = 5; // explicit typelet total = total * 2; // shadowing: new bindingconst MAX_USERS: u32 = 10; // type requiredlet (a, b) = (1, 2); // destructuringprintln!("{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.
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.
import"strconv"var i int = 42// 64-bit on 64-bit CPUsvar small int8 = 127// also int16/32/64, uint...var f float64 = 3.14var ok bool = truevar 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..u128let idx: usize = 3; // used for indexes/lengthslet f: f64 = 3.14;
let ok: bool = true;
let c: char = 'é'; // 4-byte Unicode scalarlet total = i asf64 + f; // explicit castlet 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.
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.
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. 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.
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.
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" idiomif 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;
letmut ages = HashMap::from([("ada", 36), ("linus", 54)]);
ages.insert("grace", 85); // insert/updatelet a = ages.get("bob").copied().unwrap_or(0);
ifletSome(age) = ages.get("ada") {
println!("{age}");
}
ages.remove("linus");
*ages.entry("ada").or_insert(0) += 1; // upsertfor (name, age) in &ages { // arbitrary orderprintln!("{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.
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.
score := 72var grade stringif score >= 90 {
grade = "A"
} elseif score >= 70 {
grade = "B"
} else {
grade = "C"
}
label := "fail"// no ternary operatorif score > 50 { label = "pass" }
if n := len(grade); n > 0 { // init statement
fmt.Println(n)
}
switch { // no fallthrough, no break neededcase 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"
} elseif score >= 70 {
"B"
} else {
"C"
}; // if is an expressionlet 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.
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.
for i := 0; i < 3; i++ { fmt.Print(i) }
for i := range3 { fmt.Print(i) } // Go 1.22+: 0,1,2for idx, item := range []string{"a", "b"} {
fmt.Printf("%d: %s\n", idx, item)
}
n := 10for n > 1 { n /= 2 } // the "while" loopfor { 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 in0..3 { print!("{i}"); } // 0,1,2for i in (0..=10).step_by(5) { print!("{i}"); }
for (idx, item) in ["a", "b"].iter().enumerate() {
println!("{idx}: {item}");
}
letmut n = 10;
while n > 1 { n /= 2; }
letmut 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.
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.
fngreet(name: &str, greeting: Option<&str>) -> String {
let g = greeting.unwrap_or("Hello"); // "default"format!("{g}, {name}!") // no ; = return
}
fndivmod(a: i32, b: i32) -> (i32, i32) { // tuple
(a / b, a % b)
}
fnsum(nums: &[i32]) -> i32 { // slice instead of variadic
nums.iter().sum()
}
fnmain() {
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.
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.
tax := 0.2
withTax := func(p float64) float64 {
return p * (1 + tax) // captures tax by reference
}
count := 0
inc := func() { count++ } // mutates outer countinc(); inc() // count == 2// functions are values: pass and return them
makeAdder := func(n int) func(int) int {
returnfunc(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 taxletmut count = 0;
letmut inc = || count += 1; // mutable borrowinc(); inc();
println!("{count}"); // 2let doubled: Vec<i32> = [1, 2, 3].iter().map(|x| x * 2).collect();
fnmake_adder(n: i32) -> implFn(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.
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
functionfindUser(int$id): ?User
{
return$id === 1 ? newUser("Ada") : null;
}
$user = findUser(2);
$name = $user?->name ?? "guest"; // nullsafe + defaultif ($user !== null) {
echo$user->name;
}
$city = $user?->address?->city; // null if any link is null
Go
typeUserstruct {
NamestringNick *string// optional field: nil when unset
}
funcfindUser(id int) *User { // pointer can be nilif id == 1 { return &User{Name: "Ada", Nick: new("ada")} }
returnnil
}
funcmain() {
user := findUser(2)
name := "guest"if user != nil { // no ?-> operator
name = user.Name
}
var s string// "" (zero value, not nil)var n int// 0var u *User// nil// u.Name // runtime panic: nil pointer
fmt.Println(name, s, n, u)
}
Rust
structUser { name: String }
fnfind_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");
ifletSome(u) = &user { // handle the Some caseprintln!("{}", u.name);
}
fnfirst_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.
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.
typeCounterstruct {
count int// lowercase = unexported (package-private)
}
// Pointer receiver: can mutate the structfunc (c *Counter) Increment() { c.count++ }
// Value receiver: works on a copy, read-only usefunc (c Counter) Value() int { return c.count }
funcmain() {
c := Counter{} // no "new" keyword needed
c.Increment() // Go takes &c for you
fmt.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.
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.
pubstructUser {
pub email: String, // public field
role: String, // private to this module
}
implUser {
pubfnnew(email: implInto<String>) -> Self {
Self { email: email.into(), role: "member".into() }
}
pubfnis_admin(&self) -> bool { self.role == "admin" }
}
#[derive(Debug, Default)]pubstructSettings { pub per_page: u32, pub dark_mode: bool }
fnmain() {
let u = User::new("ada@example.com");
// "optional args": set some fields, default the restlet 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.
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.
traitNotifier {
fnsend(&self, to: &str, msg: &str);
}
structEmailNotifier;
implNotifierforEmailNotifier { // explicit, like implementsfnsend(&self, to: &str, msg: &str) {
println!("Email to {to}: {msg}");
}
}
// Static dispatch: compiled once per concrete typefnalert(n: &implNotifier) { n.send("ops@example.com", "Disk almost full"); }
// Dynamic dispatch: closest to a PHP interface type hintfnalert_all(list: &[Box<dynNotifier>]) {
for n in list { n.send("ops@example.com", "Disk almost full"); }
}
fnmain() {
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.
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.
typeTimestampsstruct {
CreatedAt time.Time
}
func (t *Timestamps) Touch() { t.CreatedAt = time.Now() }
typePoststruct {
Timestamps// embedded: fields and methods are promotedTitlestring
}
funcmain() {
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.
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.
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.
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.
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.
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.
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.
// src/main.rs crate root// src/billing/mod.rs (or src/billing.rs)// src/billing/invoice.rs// src/main.rsmod billing; // files are not auto-loadeduse billing::invoice::Invoice;
fnmain() {
let i = Invoice::new(1000);
println!("{}", i.total());
}
// src/billing/mod.rspubmod invoice;
// src/billing/invoice.rspubstructInvoice { total: u64 }
implInvoice {
pubfnnew(total: u64) -> Self { Self { total } }
pubfntotal(&self) -> u64 { self.total }
pub(crate) fnaudit(&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.
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.
// $ 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).
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
*/finalclassCollection
{
/** @param list<T> $items */publicfunction__construct(privatearray$items) {}
/** @return T|null */publicfunctionfirst(): mixed
{
return$this->items[0] ?? null;
}
}
/** @var Collection<User> $users */$users = newCollection([newUser('ada@example.com')]);
$first = $users->first(); // PHPStan knows: User|null// At runtime PHP does not check T at all.
Go
typeNumberinterface {
~int | ~int64 | ~float64// type-set constraint
}
funcSum[T Number](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
typeStack[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
iflen(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]{}
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}"); }
}
structStack<T> { items: Vec<T> }
impl<T> Stack<T> {
fnnew() -> Self { Self { items: Vec::new() } }
fnpush(&mutself, v: T) { self.items.push(v); }
fnpop(&mutself) -> Option<T> { self.items.pop() }
}
fnmain() {
println!("{}", total(&[1.5, 2.5])); // 4print_all(&["a", "b"]);
letmut 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.
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.
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.
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.
// Cargo.toml: serde = { version = "1", features = ["derive"] }, serde_json = "1"use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]structUser {
id: u32,
email: String,
#[serde(skip_serializing_if = "Option::is_none")]
nickname: Option<String>,
#[serde(skip)]
password: String, // never (de)serialised
}
fnmain() -> 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 accessOk(())
}
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.
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
funcmain() {
data, err := os.ReadFile("config.txt") // []byteif 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};
fnmain() -> io::Result<()> {
let config = fs::read_to_string("config.txt")?;
print!("{config}");
letmut out = OpenOptions::new().append(true).create(true).open("out.txt")?;
writeln!(out, "hello")?;
let file = fs::File::open("access.log")?;
for line inBufReader::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.
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.
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).
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.
funcmain() {
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;
fnmain() {
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 onlyprintln!("{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.
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.
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
functionbuild(): array {
$user = newUser("Ada"); // refcount = 1$copy = $user; // same object, refcount = 2unset($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();
echomemory_get_peak_usage(true);
// End of request: PHP-FPM throws everything away anyway.
Go
typeUserstruct{ Namestring }
funcnewUser(name string) *User {
u := User{Name: name} // escapes to the heap: pointer outlives the callreturn &u
}
funcsum() int {
nums := [3]int{1, 2, 3} // stays on the stack, no GC workreturn nums[0] + nums[1] + nums[2]
}
// go build -gcflags=-m prints escape-analysis decisions// GOGC=200 GOMEMLIMIT=512MiB tune the collector at runtime
structUser { name: String }
implDropforUser { // like __destruct, but deterministicfndrop(&mutself) { println!("freeing {}", self.name); }
}
fnmain() {
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 scopeprintln!("{}", 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.
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.
typeUserstruct{ Namestring }
funcrenameCopy(u User) { u.Name = "Copy" } // value: mutates a copyfuncrename(u *User) { u.Name = "Grace" } // pointer: mutates caller's// Pointer receiver: the method can change the structfunc (u *User) SetName(n string) { u.Name = n }
funcmain() {
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)
}
fnlen(s: &String) -> usize { s.len() } // shared borrow: read-onlyfnshout(s: &mutString) { s.push('!'); } // exclusive borrow: may mutate// Lifetime 'a: the returned &str may not outlive either inputfn longest<'a>(a: &'astr, b: &'astr) -> &'astr {
if a.len() >= b.len() { a } else { b }
}
fnmain() {
letmut name = String::from("Ada");
let n = len(&name); // any number of & borrows at once...shout(&mut name); // ...or exactly one &mut, never bothprintln!("{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.
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 = newCart();
$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 = newWeakMap();
$totals[$a] = $a->total();
unset($a, $b); // entry disappears from $totalsechocount($totals); // 0
Go
typeNodestruct {
ValintNext *Node// pointer: optional, shared, recursive
}
funcmain() {
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])
}
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
#[derive(Debug)]enumList { Cons(i32, Box<List>), Nil } // Box: heap + recursive typefnmain() {
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 threadlet alias = Rc::clone(&cart); // refcount 2
alias.borrow_mut().push(30); // checked at runtimeprintln!("{:?} 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.
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 ($pidsas$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
funcmain() {
files := []string{"a.csv", "b.csv", "c.csv"}
results := make(chanstring, len(files))
var wg sync.WaitGroupfor _, 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)
}
}
use std::sync::mpsc;
use std::thread;
fnmain() {
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 heredrop(tx); // close the channelfor 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.
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.
// tokio = { version = "1", features = ["full"] }, reqwest = "0.12"asyncfnfetch(url: &str) -> reqwest::Result<String> {
reqwest::get(url).await?.text().await
}
#[tokio::main]asyncfnmain() {
// join!: run both futures concurrently and wait for bothlet (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 -> Resultprintln!("{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.
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
useIlluminate\Support\Facades\Cache;
// Distributed lock (Redis/DB): one worker at a time across serversCache::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
typeCounterstruct {
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
)
funcGetConfig() *Config {
once.Do(func() { cfg = loadConfig() }) // runs exactly once
total.Add(1)
return cfg
}
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();
fnmain() {
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.
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 = newGuzzleHttp\Client(['timeout' => 5.0]);
// Cancelling work running elsewhere = a flag the job checks:// if (Cache::get("import:{$id}:cancelled")) return;
Go
funchandler(w http.ResponseWriter, r *http.Request) {
// r.Context() is cancelled if the client disconnects
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defercancel()
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: ... }
use std::time::Duration;
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;
asyncfnslow_call() -> u32 { sleep(Duration::from_secs(5)).await; 42 }
#[tokio::main]asyncfnmain() {
matchtimeout(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(asyncmove {
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.
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.
funcmain() {
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};
asyncfnshow_user(Path(id): Path<u64>) -> Json<Value> {
Json(json!({ "id": id, "name": "Ada" })) // bad id -> automatic 400
}
#[tokio::main]asyncfnmain() {
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.
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 = newPDO('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
)
typeUserstruct {
ID int64NamestringEmailstring
}
funcfindUser(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 positionif 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)]structUser { id: i64, name: String, email: String }
asyncfnfind_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 ?.
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.
typeUserstruct {
Namestring`json:"name" db:"user_name"`
}
funccolumns(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=StatustypeStatusintconst (
DraftStatus = iotaPublished
)
// serde = { version = "1", features = ["derive"] }#[derive(Debug, Clone, PartialEq, serde::Serialize)]// impls written for youstructUser {
#[serde(rename = "user_name")]// read by the derive macro
name: String,
}
// macro_rules!: pattern-matching on syntaxmacro_rules! hashmap {
($($k:expr => $v:expr),* $(,)?) => {{
letmut m = std::collections::HashMap::new();
$( m.insert($k, $v); )*
m
}};
}
fnmain() {
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.
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).
typeMoneystruct {
Centsint64Curstring
}
// fmt.Stringer: used by Println, %v and %sfunc (m Money) String() string {
return fmt.Sprintf("%s %.2f", m.Cur, float64(m.Cents)/100)
}
// error is just an interface: any type with Error() stringtypeInsufficientFundsstruct{ NeedMoney }
func (e InsufficientFunds) Error() string { return"need " + e.Need.String() }
// io.Writer: files, sockets, buffers, http.ResponseWriter...funcreport(w io.Writer, m Money) { fmt.Fprintln(w, m) }
// report(os.Stdout, m); report(&bytes.Buffer{}, m)
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.outfuncBenchmarkSum(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/
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.
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; // 7echo$ffi->abs(-42), PHP_EOL; // 42
package main
/*
#include <stdlib.h>
#include <string.h>
*/import"C"import (
"fmt""unsafe"
)
funcmain() {
cs := C.CString("gopher") // allocated in C memory: free it yourselfdefer 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))
}
use std::ffi::{CString, c_char};
unsafeextern"C" { // 2024 edition: `unsafe extern`fnstrlen(s: *const c_char) -> usize;
safe fnabs(j: i32) -> i32; // declared safe to call
}
fnmain() {
let s = CString::new("ferris").unwrap();
let n = unsafe { strlen(s.as_ptr()) }; // you vouch the pointer is validprintln!("{n} {}", abs(-42));
let x = 7;
let p = &x as *consti32; // 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.
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.
# Dockerfile — one static binary, no runtime neededFROM golang:1 AS build
WORKDIR /src
COPYgo.mod go.sum ./
RUNgo mod download
COPY . .
RUN CGO_ENABLED=0go 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 buildFROM rust:1-trixie AS build
WORKDIR /src
COPY . .
RUNcargo build --release --locked
# Same Debian release as the build stage, or the binary fails on glibcFROM 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.