home/ atoms/ wgsl-declaration-keywords

WGSL declares data with var (mutable storage), let (immutable value), and const (compile-time constant)

WGSL is strictly typed — it requires knowing the type of every variable, struct field, function parameter, and return type — and it offers three declaration keywords with distinct meanings. var declares a variable that has storage and so is mutable. let declares a constant value that cannot be reassigned but is computed at runtime. const is not a variable at all but a compile-time constant, and cannot be used for anything computed at runtime. The distinction guides how the shader compiler treats each. Note WGSL also has no ternary operator — use select(falseExpression, trueExpression, condition) instead — and ++/— are statements, not expressions.

Examples

const PI = 3.14159; is a compile-time constant. let scale = uniforms.scale; is a runtime immutable value. var position = vec3(0.0); is mutable storage. let a = select(lo, hi, condition); replaces a ternary (note: false value comes first).

Assessment

In WGSL, what is the difference between let and var, and between let and const? Write a WGSL line declaring a compile-time PI constant, and one using select() to pick between two values.

“WGSL requires knowing the types of every variable, struct field, function parameter and function return type”