typesjuliacomposite-types

Julia: Passing a field of a composite type as argument


Consider the following example

struct valueStruct
    a::Vector{Float64}
    a2::Vector{Float64} 
end

values = valueStruct(ones(10), ones(10));
values2 = 1:10;

function testFunc!(values, values2)
    values.a .= values.a .* values2;
end

I want to create a function testFunc2! such that it can take in a field instead of the entire object. For example: testFunc2!(values.a, values2). However, I keep getting this error:

LoadError: LoadError: syntax: "values.a" is not a valid function argument name.

I want to do this because in my actual code, I want to apply testFunc! recursively in a loop on the struct values, e.g. testFunc!(values.a2, values.a). I know that I can do soemthing like this:

function testFunc!(values, values2, n)
    values.a .= values.a .* values2;
    for i = 1:n
        values.a2 .= values.a;
    end
end

However, that's not what I want. In my actual code, I need to have a flexible function such that I can apply it to the fields of a type. Is that possible?


Solution

  • I don't understand the problem. This works fine:

    struct ValueStruct
        a::Vector{Float64}
        a2::Vector{Float64} 
    end
    
    function testfunc!(a, b)
        a .*= b
    end
    
    values = ValueStruct(ones(10), ones(10))
    values2 = 1:10
    testfunc!(values.a, values2)
    

    BTW: There is a strong convention in Julia that type names should be capitalized: ValueStruct, not valueStruct. There is also a convention that function names should be all lowercase, though that seems to be less strict.