Home > Blockchain >  How to create a function return nothing in Julia?
How to create a function return nothing in Julia?

Time:10-04

When I create a function in Julia, I print something in the function and don't return anything. But the result is the function print what I want and also return 'nothing'. What can I do to make the function just print what I want without return 'nothing'?

CodePudding user response:

There is always a return value from a function. When there is no explicit return statement, the value of the last expression in the function is returned. This is probably what you're seeing here: if the print statement is the last line of your function, since print's return value is nothing, that becomes the return value of your function too.

If you just don't want the nothing shown at the end of the output,then please paste the code you're using that leads to this behaviour, and we can figure out how to suppress this output of nothing from appearing.

CodePudding user response:

Some additional comment to the answer by @sundar.

In other words nothing is the value meaning that the function did not return anything. Consider this Julia session:

julia> function f()
       end
f (generic function with 1 method)

julia> res = f()

julia> dump(res)
Nothing nothing

By default nothing is displayed as an empty output:

julia> res     

This however changes when res ends up interpolated in another string:

julia> "$res"  
"nothing"      

For cases like above consider using something such as:

julia> "$(something(res,""))"
""
  • Related