Struct

Julia intermedio

Anthony Markham

Quantitative Developer

Struct - introduzione

  • Gli struct sono un tipo composto.
  • Sono come altri tipi, ma con quanti campi vuoi.
  • Con un tipo composto creiamo poi un oggetto, una rappresentazione del tipo.
Julia intermedio

Struct - sintassi

  • Usa la keyword struct per definire una struttura.
  • Ogni campo nello struct è indentato dentro la dichiarazione.
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(steve.height)
180
Julia intermedio

Struct - typeof dell'oggetto

  • Il tipo di steve è Person.
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(typeof(steve))
Person
Julia intermedio

Struct - immutabilità

  • Uno struct è immutabile di default.
# È il compleanno di Steve!
steve = Person(18, 180, "London")
steve.age = 19
setfield!: immutable struct of type Person cannot be changed
Julia intermedio

Struct - mutabili

  • Usa la keyword mutable per creare uno struct mutabile.
mutable struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
steve.age = 19
println(steve)
Person(19, 180, "London")
Julia intermedio

Struct - tipi dei campi

  • Possiamo specificare un tipo per ogni campo nella definizione dello struct.
mutable struct Person
    age::Int64
    height::Int64
    location::String
end
steve = Person(18.5, 180, "London")
InexactError: Int64(18.5)
Julia intermedio

Passiamo alla pratica !

Julia intermedio

Preparing Video For Download...