Private fields with `fieldnames` and `propertynames`

everywhere write that with the help of propertynames I can set public and private fields, but how legal is it to do this with fieldnames? Struct the structure stores its fields in Struct*.name.names and I can overload fieldnames, so I can redefine fieldnames however I want?

You cannot redefine fieldnames or getfield, those are two of the very few builtin functions in julia which cannot be extended or changed by users.

in julia 1.8 I can:

julia> struct Foo
           a::Int64
           b::String
       end

julia> fieldnames(Foo)
(:a, :b)

julia> Base.fieldnames(::Type{Foo}) = (:a,)

julia> fieldnames(Foo)
(:a,)

Oh right, my mistake, it’s just getfield, not fieldnames I suppose. I would strongly recommend against overloading that, I don’t think you’re supposed to do it and you could break things.

2 Likes

Then how to change the output list of fields in a type? (I only have type information, I can’t use propertynames)

Just don’t do it.

1 Like