soli
soli

Reputation: 403

Change the value of the filed of composite type using `Symbol` or `String` in Julia

How can I change the value of the field of composite type using Symbol or String?

Example: If I have MyType,

type MyType
   x
end
mt=MyType(0)

I know I can change the value by mt.x=1.

However, how can I do the same thing using a variable changed_fieldname = :x or changed_fieldname = x?

I don't want to directly write the name of the field as mt.x=1.

Upvotes: 5

Views: 63

Answers (1)

mbauman
mbauman

Reputation: 31342

Use setfield!:

julia> mt=MyType(0)
MyType(0)

julia> changed_fieldname = :x
       setfield!(mt, changed_fieldname, 1)
1

julia> mt
MyType(1)

Upvotes: 6

Related Questions