Setting value to named field in Julia - setfield() Method

Last Updated : 12 Jul, 2025

The setfield() is an inbuilt function in julia which is used to assign a value x to a named field in value of composite type. The value must be mutable and x must be a subtype of fieldtype(typeof(value), name)
 

Syntax: 

setfield(value, name::Symbol, x)


Parameters: 

  • value: Specified value of composite type.
  • name::Symbol: Specified symbol.
  • x: Specified value.


Returns: It returns the assigned value x to a named field in value of composite type. 
 
Example 1: 

Python
# Julia program to illustrate 
# the use of setfield() method
 
# Getting the assigned value 'x' to 
# a named field in value of composite type.
mutable struct MyMutableStruct
           field::Int
       end

a = MyMutableStruct(1);
setfield (a, :field, 123);
println(getfield(a, :field))

Output: 
 

123


Example 2: 

Python
# Julia program to illustrate 
# the use of setfield() method
 
# Getting the assigned value 'x' to 
# a named field in value of composite type.
a = 5//3
println(setfield (a, :num, 123))

Output: 
 

ERROR: LoadError: type Rational is immutable
while loading /home/cg/root/5090533/main.jl, in expression starting on line 7


 

Comment