What does the return keyword do in a let/begin block?

Hi, I couldn’t find in the documentation an explanation to this behavior.

let
    "let block without return"
end |> println
# OUTPUT: let block without return

let
    return "let block with return"
end |> println
# OUTPUT: "let block with return"
# NOTE: the double quotes are actually printed

let
    "let block without return"
end |> typeof |> println
# OUTPUT: String

let
    return "let block with return"
end |> typeof |> println
# OUTPUT: "let block with return"
# NOTE: What is going on?

var1 = let
    "let block without return"
end
println("`var1` is assigned to: ", var1)
# OUTPUT: `var1` is assigned to: let block without return

var2 = let
    return "let block with return"
end
println("`var2` is assigned to: ", var2)
# OUTPUT: ERROR: LoadError: UndefVarError: var2 not defined[...]
# NOTE: What is going on?

A similar behaviour occurs with begin blocks.

I’m using julia 1.6.1

Thanks!

1 Like

https://github.com/JuliaLang/julia/issues/30499

3 Likes

What is the correct way of assigning to a variable in the context of the original question? Is an anonymous function the only way, for instance when I want to return from a for loop?

var1 = (() -> begin
    for_loop
        condition && return some_val
    end)()

Why not just the for loop itself?

julia> var1 = let x
           for i in 1:5
               (i == 4) && (x = i; break)
           end
           x
       end
4
3 Likes

Thank you. I was not aware that let could be used in this way.

I think this is worth to have in the docs: https://github.com/JuliaLang/julia/pull/43094