我有一个功能
function foo(a)
if a > 5
a = 5
end
some_more_code
end
Run Code Online (Sandbox Code Playgroud)
如果 -if
语句是true
我想结束该函数但我不想返回任何内容 - 更改 的值a
就是我所需要的。
我怎么做?
您可以编写(请注意,我还更改了函数定义的语法,使其更符合 Julia 风格的标准):
function foo(a)
if a > 5
a = 5
return
end
# some_more_code
end
Run Code Online (Sandbox Code Playgroud)
只使用return
关键字,后面没有任何表达式。准确地说,在这种情况下,Julia 会从函数中返回nothing
类型值Nothing
(它不会打印在 REPL 中,用于表示您不想从函数中返回任何内容)。
请注意, 的值a
只会在本地更改(在函数范围内),因此在函数之外它将保持不变:
julia> function foo(a)
if a > 5
a = 5
return
end
# some_more_code
end
foo (generic function with 1 method)
julia> x = 10
julia> foo(x)
julia> x
10
Run Code Online (Sandbox Code Playgroud)
为了使更改在函数之外可见,您必须使其a
成为某种容器。这种情况的典型容器是Ref
:
julia> function foo2(a)
if a[] > 5
a[] = 5
return
end
# some_more_code
end
foo2 (generic function with 1 method)
julia> x = Ref(10)
Base.RefValue{Int64}(10)
julia> foo2(x)
julia> x[]
5
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
83 次 |
最近记录: |