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
.
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 .
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.
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.
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.
Use setfield!
:
julia> mt=MyType(0)
MyType(0)
julia> changed_fieldname = :x
setfield!(mt, changed_fieldname, 1)
1
julia> mt
MyType(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With