
If the computation of the default value does not have side effects, unwrap_or() can be used as a more concise (and without optimizations, more efficient) choice. Unwrap_or_else() serves a similar purpose as the null coalescing operator in other languages. While there's no null in Rust, tagged unions are used for the same purpose. This is what led Perl/Python/Javascript to add a separate operator while Ruby hasn't. In comparison, Perl/Python/Javascript, which also have the latter property, have other false-like values (0 and empty string), which make || differ from a null-coalescing operator in many more cases (numbers and strings being two of the most frequently used data types). Ruby's || operator evaluates to its first operand when true-like. Ruby conditionals have only two false-like values: false and nil (where 'false' is not the same as 0). Ruby does not have a null-coalescing operator, but its || and ||= operators work the same way except on Booleans. $myVar = $null $x = $myVar ? "something" # assigns "something" Ruby Otherwise, the value of parameter is substituted": In Bourne shell (and derivatives), "If parameter is unset or null, the expansion of word is substituted.

In contrast to the ternary conditional if operator used as x ? x : y, but like the binary Elvis operator used as x ?: y, the null coalescing operator is a binary operator and thus evaluates its operands at most once, which is significant if the evaluation of x has side-effects.Įxamples by languages Bourne-like Shells This behavior allows a default value to be defined for cases where a more specific value is not available. While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.0, Perl as of version 5.10, Swift, and PHP 7.0.0.
