Fields of a struct

julia> fieldnames(typeof(state))
(:hamiltonian, :replicas, :maxlength, :r_strat, :s_strat, :τ_strat, :post_step, :replica)

julia> state.step
5000

julia> state.laststep
5000

It is strange that while the variable ‘state’ as a datatype has no field name ‘step’, it does has a value for ‘state.step’.

What is wrong?

Take a look at propertynames. Note that it expects an instance of a type and not a type.

1 Like
julia> propertynames(state)
(:hamiltonian, :replicas, :maxlength, :r_strat, :s_strat, :τ_strat, :post_step, :replica)

julia> fieldnames(typeof(state))
(:hamiltonian, :replicas, :maxlength, :r_strat, :s_strat, :τ_strat, :post_step, :replica)

Seems like whoever defined the type that state has overloaded getproperty, but didn’t make that known through propertynames (which they should). Open an issue at the package repo in question.

# Allow setting step, laststep, dτ, shift from QMCState.
function Base.getproperty(state::QMCState, key::Symbol)
    if key == :step
        step = state.replicas[1].params.step
        return step
    elseif key == :laststep
        laststep = state.replicas[1].params.laststep
        return laststep
    elseif key == :maxlength
        return getfield(state, :maxlength)[]
    elseif key == :dτ
        return state.replicas[1].params.dτ
    elseif key == :shift
        return state.replicas[1].params.shift
    else
        return getfield(state, key)
    end
end
function Base.setproperty!(state::QMCState, key::Symbol, value)
    if key == :step
        for r in state.replicas
            r.params.step = value
        end
        return value
    elseif key == :laststep
        for r in state.replicas
            r.params.laststep = value
        end
        return value
    elseif key == :dτ
        for r in state.replicas
            r.params.dτ = value
        end
        return value
    elseif key == :shift
        for r in state.replicas
            r.params.shift = value
        end
        return value
    elseif key == :maxlength
        getfield(state, :maxlength)[] = value
        return value
    else
        # This will error
        return setfield!(state, key, value)
    end
end

you should also have:

Base.propertynames(::QMCState) = (:step, :laststep, :maxlength, :dr, :shift)