Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
Both Rust and PHP have a boolean type. The main difference is how strict the type system is and how other values convert to boolean.
Rust
fn main() {
let is_rust_fun: bool = true;
let is_compiled: bool = false;
if is_rust_fun {
println!("Rust is fun!");
}
// Logical operators
let a = true && false; // false
let b = true || false; // true
let c = !true; // false
println!(
"is_rust_fun={}, is_compiled={}, a={}, b={}, c={}",
is_rust_fun, is_compiled, a, b, c
);
// No implicit conversion: this would not compile
// if 1 { } // Error: expected bool, found integer
}
Rust's bool is a distinct type. Integers and other types do not implicitly convert to bool.
PHP
<?php
$is_rust_fun = true;
$is_compiled = false;
if ($is_rust_fun) {
echo "Rust is fun!\n";
}
$a = true && false; // false
$b = true || false; // true
$c = !true; // false
// PHP allows many values as "truthy" or "falsy"
if (1) { } // Truthy
if (0) { } // Falsy
if ("") { } // Falsy
if ("hello") { } // Truthy
if ([]) { } // Falsy (empty array)
PHP treats many values as truthy or falsy when used in a boolean context.
Comparison
- Rust:
boolonly; no implicit conversion from numbers or strings. - PHP:
boolplus truthy/falsy rules for other types in boolean context.
In Rust you must use explicit comparisons (e.g. if x != 0) instead of relying on truthiness.
References
What's next
Next: Characters.
From PHP to Rust — Rust Syntax and Functions