Change the value of the submitted compound form using the Symbol or String symbol in Julia

How to change the value of a composite type field using Symbol or String ?

Example: if I have MyType ,

 type MyType x end mt=MyType(0) 

I know that I can change the value to mt.x=1 .

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

I do not want to write the field name directly as mt.x=1 .

+5
source share
1 answer

Use setfield! :

 julia> mt=MyType(0) MyType(0) julia> changed_fieldname = :x setfield!(mt, changed_fieldname, 1) 1 julia> mt MyType(1) 
+6
source

Source: https://habr.com/ru/post/1267034/


All Articles