assert
assert(mixed $assertion, Throwable|string|null $description = null): bool
断言一个「理应恒真」的预期,失败抛 AssertionError;zend.assertions=1 才真正执行,-1(生产推荐)在编译期消失、零成本。
C C23
C23
#include <assert.h>
#include <stdio.h>
int main(void) {
assert(1 + 1 == 2); /* 定义 NDEBUG 时被整体编译掉 */
printf("still running\n");
return 0;
}
输出
still running
C++ C++26
C++26
#include <cassert>
#include <iostream>
int main() {
assert(1 + 1 == 2); // 随 NDEBUG 消失
static_assert(2 > 1, "compile-time assertion"); // 恒检查,零运行时代价
std::cout << "still running" << std::endl;
return 0;
}
输出
still running
C# v11.0.100
v11.0.100
// C#:Debug.Assert 在 Release 构建中消失;Trace.Assert 永远被编译进来
System.Diagnostics.Debug.Assert(1 + 1 == 2);
System.Diagnostics.Trace.Assert(1 + 1 == 2);
Console.WriteLine("still running");
输出
still running
Go v1.27.4
v1.27.4
package main
import "fmt"
func main() {
// Go:没有 assert 关键字——语言立场是显式错误处理
if 1+1 != 2 {
panic("math broke") // 最接近的东西,而且永远「开着」
}
fmt.Println("still running")
}
输出
still running
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
// Java:assert 默认关闭——要加 -ea 参数才会执行
assert 1 + 1 == 2;
System.out.println("still running");
}
}
输出
still running
JavaScript v26.13.1
v26.13.1
// JS:console.assert 只在开发者工具里打日志;Node 的 assert.ok 会抛 AssertionError
const assert = require("node:assert");
assert.ok(1 + 1 === 2);
console.log("still running");
输出
still running
PHP v8.6.0
v8.6.0
// assert:一条可能在生产环境消失的预期(zend.assertions=-1 会把它编译掉)
var_dump(assert(1 + 1 === 2)); // 无论检查真执行还是被编译掉,都返回 true
echo "still running\n";
输出
bool(true) still running
Python v3.15.2
v3.15.2
# Python:用 -O 运行时 assert 会被整体剥掉
assert 1 + 1 == 2
print("still running")
输出
still running
Rust v1.99.1
v1.99.1
fn main() {
// Rust:assert! 恒在;debug_assert! 在 release(此处 -O)中被编译掉
assert_eq!(1 + 1, 2);
debug_assert!(1 + 1 == 2);
println!("still running");
}
输出
still running
TypeScript v26.13.1
v26.13.1
// TS:同 JS——用 node:assert 的 assert.ok
import assert from "node:assert";
assert.ok(1 + 1 === 2);
console.log("still running");
输出
still running
语言差异说明
C:assert(3),定义 NDEBUG 后整句消失——家传语义。
C++:同 C,另有 static_assert 编译期断言(恒在、零运行时代价)。
C#:Debug.Assert 带 [Conditional("DEBUG")],Release 构建直接消失;Trace.Assert 恒在;失败在服务端环境写作日志。
Go:没有 assert——语言立场是显式错误处理;最接近的 panic 永远「开着」。
Java:assert 默认关闭,要 -ea 才执行——与 PHP 的 zend.assertions 同款「消失」语义。
JavaScript:console.assert 只在 DevTools 打日志、不中断;Node 的 assert.ok() 会抛 AssertionError(示例用之)。
PHP:生产用 zend.assertions=-1(编译期消失);不要拿 assert 做输入校验——关掉后检查就不存在了;失败抛 AssertionError(Error 族);PHP 8.0 起字符串断言被移除(曾是 eval,安全隐患);8.3 起 assert.* 系列 ini 全部弃用。
Python:assert 语句带 -O 即整体剥掉;正因如此别用它做数据校验。
Rust:assert!/assert_eq! 恒在(release 亦然);debug_assert! 只在 debug 构建存在——本条目 rustc -O 实跑时它已被编译掉。
TypeScript:同 JavaScript。