如何在 Julia 中获取 `do` 块的值?

DVN*_*old 2 scope julia

我有一个 HDF5 文件,我想从中读取 2 个数组。如何使用do块表示法获取它们?

using HDF5

function myfunc()
    h5open("path", "r") do f
        a = read(f, "a")
        b = read(f, "b")
    end

    # ... do some more processing of a, b
    return a, b
end
Run Code Online (Sandbox Code Playgroud)

如果我运行它,它会在 do 块之后出错a not defined。我如何获取值以便我可以在之后处理它们,而无需将完整计算包装在do块中?

fre*_*kre 5

do块只是语法创建被作为第一个参数传递的匿名功能(h5open在此case`)。就像常规函数一样,您需要从要在“外部”使用的匿名函数返回任何值:

# Function to mimic Base.open, HDF5.h5open etc
function open(f)
    return f()
end

function g()
    a, b = open() do
        c = "hello"
        d = "world"
        return c, d # returns from the "do"-anonymous function
    end
    return a, b
end
Run Code Online (Sandbox Code Playgroud)