Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 241
sholi Avatar asked Apr 21 '17 18:04

sholi


People also ask

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

What does the splat operator do Julia?

The "splat" operator, ... , represents a sequence of arguments. ... can be used in function definitions, to indicate that the function accepts an arbitrary number of arguments. ... can also be used to apply a function to a sequence of arguments.

How do you determine the type of variable in Julia?

We can use the function typeof(x) to find the data type of the variable x. UInt32julia> typeof(5.) On top of these REAL and COMPLEX datatypes are also implemented.

What is the type of a function in Julia?

Method Tables Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table.


1 Answers

Use setfield!:

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

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

julia> mt
MyType(1)
like image 152
mbauman Avatar answered Sep 29 '22 05:09

mbauman