Struct is a new type for defining custom types by combining inbuilt native types.

This is also called Records or composite type in another programming language

How to define a struct in Julia

Struct is a keyword used to define new types.

Syntax:

struct NewType
    property1
    property2::datatype
    property3::datatype
end

NewType is a custom datatype that holds multiple properties. Properties declared with either datatype or without datatype(Any). property1 is of Any type. :: operators assign type to a variable or expression Once the new type is created, We can create an object using the constructor.

variable = NewType(value1,value2,value3)
struct Employee
    id::Int64
    name::string
end

variable = Employee(3, "john")
println(variable)

Output

Employee(3, "john")

properties can be accessed using variable.property syntax

variable = Employee(3, "john")
println(variable.id) # 3
println(variable.name) # john

How do you change the values of a struct object?

struct Employee
    id::Int64
    name::String
end

variable = Employee(3, "john")

println(variable)
variable.name="ram"
println(variable)

It throws an error ERROR: LoadError: setfield!: immutable struct of type Employee cannot be changed

Employee(3, "john")
ERROR: LoadError: setfield!: immutable struct of type Employee cannot be changed
Stacktrace:
 [1] setproperty!(x::Employee, f::Symbol, v::String)
   @ Base ./Base.jl:39
 [2] top-level scope
   @ ~/SevereGrimyExpertise/main.jl:9
in expression starting at /home/runner/SevereGrimyExpertise/main.jl:9

by default struct types are immutable. You can not change its value.

Then, How do you declare a mutable struct

declare struct using mutable keyword

mutable struct type example:

mutable struct Employee
    id::Int64
    name::String
end

variable = Employee(3, "john")

println(variable)
variable.name="ram"
println(variable)

Output:

Employee(3, "john")
Employee(3, "ram")

How to pass Struct type to functions

The function contains a struct as an argument It contains arguments with :: operator

mutable struct Employee
    id::Int64
    name::String
end

variable = Employee(3, "john")

function print(e::Employee)
   println(e.id)
   println(e.name)

end

print(variable)