return
return ends the current custom command or closure early and makes its argument the result. Without an argument, the result is null. Since the value of the last expression is returned implicitly (see Implicit Return), return is only needed to leave early.
See also: return command help and Control Flow - return in the Book.
def sign [n: int] {
if $n < 0 { return "negative" }
if $n == 0 { return "zero" }
"positive"
}
[(sign -5) (sign 0) (sign 7)]
# => ╭───┬──────────╮
# => │ 0 │ negative │
# => │ 1 │ zero │
# => │ 2 │ positive │
# => ╰───┴──────────╯Language Notes
returnleaves the nearest enclosing custom command or closure. Blocks that belong toif,match,try,for,whileandloopare not functions, so areturninside them leaves the whole command, including any loop it is in:def first-even [nums: list<int>] { for n in $nums { if $n mod 2 == 0 { return $n } } null } first-even [1 3 4 5 6] # => 4A closure is a function of its own. A
returninside the closure passed toeach(orwhere,do,reduce, ...) only ends that call of the closure. The surrounding command keeps running:def labels [] { [1 2 3] | each {|x| if $x == 2 { return "two" }; $x } } labels # => ╭───┬─────╮ # => │ 0 │ 1 │ # => │ 1 │ two │ # => │ 2 │ 3 │ # => ╰───┴─────╯let check = {|n| if $n > 0 { return 'positive' }; 'non-positive' } [(do $check 3) (do $check (-3))] # => ╭───┬──────────────╮ # => │ 0 │ positive │ # => │ 1 │ non-positive │ # => ╰───┴──────────────╯returntakes at most one value. To return several values, return a list or a record:def f [] { return 1 2 } # => Error: nu::parser::extra_positional # => # => × Extra positional argument. # => ╭─[repl_entry #1:1:21] # => 1 │ def f [] { return 1 2 } # => · ┬ # => · ╰── extra positional argument # => ╰──── # => help: Usage: return (return_value)A bare
returnreturnsnull:def f [] { return } f | describe # => nothingAt the top level of a script (or a REPL entry),
returnstops the rest of that script or entry. Its value becomes the result:print before; return 5; print after # => before # => 5A
finallyblock of a surroundingtrystill runs, and the returned value is kept:def f [] { try { return 1 } finally { print "finally ran" }; 2 } f # => finally ran # => 1