setfield!

setfield!(value, name::Symbol, x)

Assign x to a named field in value of composite type. The syntax a.b = c calls setfield!(a, :b, c), and the syntax a.(b) = c calls setfield!(a, b, c).

Examples

  1. Set a field in a composite type:

    julia> struct Person
              name::String
              age::Int
          end
    
    julia> p = Person("Alice", 25)
    Person("Alice", 25)
    
    julia> setfield!(p, :name, "Bob")
    Person("Bob", 25)

    In this example, the setfield! function is used to modify the name field of the Person struct.

  2. Update a field using dot syntax:

    julia> struct Point
              x::Float64
              y::Float64
          end
    
    julia> pt = Point(2.0, 3.5)
    Point(2.0, 3.5)
    
    julia> pt.x = 4.2  # Equivalent to setfield!(pt, :x, 4.2)
    4.2
    
    julia> pt
    Point(4.2, 3.5)

    Here, the dot syntax is used to update the x field of the Point struct.

  3. Modify a field using an array of symbols:

    julia> struct Car
              make::String
              model::String
              year::Int
          end
    
    julia> c = Car("Toyota", "Corolla", 2020)
    Car("Toyota", "Corolla", 2020)
    
    julia> setfield!(c, [:make, :model], ["Honda", "Accord"])
    Car("Honda", "Accord", 2020)

    In this example, an array of symbols is used to specify multiple fields to be modified simultaneously.

Common mistake example:

julia> struct Rectangle
           width::Float64
           height::Float64
       end

julia> rect = Rectangle(5.0, 7.0)
Rectangle(5.0, 7.0)

julia> setfield!(rect, :length, 10.0)
ERROR: type Rectangle has no field length

In this case, the mistake is trying to set a field (length) that does not exist in the Rectangle struct. Make sure to specify the correct field name when using setfield!.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: