当参数可能是两种类型之一时如何声明(和传递)Julia 函数参数

Ces*_*sar 2 parameters function julia

我的目标是将IOStream变量传递给 Julia 函数(如果我想写入打开的文件),或nothing(或可能被视为空值或 null 值的其他内容)。原因是我可能会多次调用此函数,并且无论我输入该函数多少次,都希望保持文件句柄打开。如果意图不是写入文件,我会简单地将nothing 指示传递给函数不要尝试写入文件。

我试过声明为:

function f(x, y, f)
Run Code Online (Sandbox Code Playgroud)

并作为:

function f(x, y, f::IOStream)
Run Code Online (Sandbox Code Playgroud)

并作为:

function f(x, y, f::Any)
Run Code Online (Sandbox Code Playgroud)

同时通过在一个变量设置为nothingIOStream从所得

open("filename.txt", "a")
Run Code Online (Sandbox Code Playgroud)

陈述。在所有情况下,我都会收到某种错误。有没有其他方法可以实现我的目标,还是应该使用不同类型的函数声明/调用?

Prz*_*fel 6

函数和参数的名称不应相同。无论如何,有两种方法 - 使用类型Union或多重分派。

因此,您的代码可以是:

function f(x, y, fs::Union{IOStream,Nothing}=nothing)
    #code goes here
end
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

function f(x, y, fs::IOStream)
    #code goes here
end
function f(x, y, fs::Nothing)
    #code goes here
end
Run Code Online (Sandbox Code Playgroud)

除了第二个功能,您也可以这样做:

function f(x, y)
    #code goes here
end
Run Code Online (Sandbox Code Playgroud)