Calling fields of a composite type (data structure) in Julia?

Viewed 57

If I write a function in Julia that returns an object x with multiple fields, is there any way to call the values of specific fields of that object? I am not sure how to do this, as the variable name will specifically be local to the function; I have attached an image further explaining this.

enter image description here

1 Answers

Your variable is local (within function scope) and perhaps you want to have a global variable.

function c1()
    Data(10 ,20) 
end
function c2()
    global z2 = Data(100 ,200) # note that using globals is discouraged in Julia
end

Now you have:

julia> z1 = c1(); # recommended approach

julia> z1.x
10

julia> c2();

julia> z2.x
100

For more details see: https://docs.julialang.org/en/v1/manual/variables-and-scoping/

Related