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

How to declare (and pass) Julia function parameters when the parameter could be one of two types

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

我试过声明为:

function f(x, y, f)

并作为:

function f(x, y, f::IOStream)

并作为:

function f(x, y, f::Any)

同时将变量集传递给 nothing 或由

产生的 IOStream
open("filename.txt", "a")

声明。在所有情况下,我都会遇到某种错误。有没有其他方法可以实现我的目标,或者我应该使用不同类型的函数 declaration/call?

函数和参数的名称不能相同。不管怎样,有两种方法——要么使用 type Union 要么使用 multiple dispatch.

因此您的代码可以是:

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

或者你可以这样做:

function f(x, y, fs::IOStream)
    #code goes here
end
function f(x, y, fs::Nothing)
    #code goes here
end

除了第二个函数你还可以这样做:

function f(x, y)
    #code goes here
end