Structs in Julia

Based on the provided instructions and the given input with a target language of Julia, here is the extracted Go code translated to Julia with an appropriate explanation in Markdown format suitable for Hugo:


Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

Example in Julia

This Person mutable struct type has name and age fields.

mutable struct Person
    name::String
    age::Int
end

new_person constructs a new Person struct with the given name.

function new_person(name::String)::Person
    p = Person(name, 42)
    return p
end

This syntax creates a new struct.

println(Person("Bob", 20))

You can name the fields when initializing a struct.

println(Person(name="Alice", age=30))

Omitted fields will be zero-valued.

println(Person(name="Fred", age=0))

An & prefix yields a pointer to the struct (in Julia, we simply use the struct).

println(Person(name="Ann", age=40))

It’s idiomatic to encapsulate new struct creation in constructor functions.

println(new_person("Jon"))

Access struct fields with a dot.

s = Person("Sean", 50)
println(s.name)

You can also use dots with struct references - Julia automatically handles the reference.

sp = s
println(sp.age)

Structs are mutable.

sp.age = 51
println(sp.age)

If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous struct type. This technique is commonly used for table-driven tests.

dog = (; name = "Rex", isGood = true)
println(dog)

Running the Code

To run the Julia code, you can simply execute the script using the julia command.

$ julia structs.jl

The expected output of running the code would be:

Person("Bob", 20)
Person("Alice", 30)
Person("Fred", 0)
Person("Ann", 40)
Person("Jon", 42)
Sean
50
51
(name = "Rex", isGood = true)

Now that we can run and build basic Julia programs, let’s learn more about the language.

Next example: Methods.