结构体

Julia 中级

Anthony Markham

Quantitative Developer

结构体 - 概述

  • 结构体是复合类型的一种应用。
  • 类似其他类型,但可包含任意数量的字段。
  • 使用复合类型可以创建对象,即该类型的一个实例。
Julia 中级

结构体 - 语法

  • 使用 struct 关键字定义结构体。
  • struct 内的每个字段在声明体内缩进。
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(steve.height)
180
Julia 中级

结构体 - 对象类型

  • steve 的类型是 Person
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(typeof(steve))
Person
Julia 中级

结构体 - 不可变性示例

  • 结构体默认不可变。
# Steve 过生日了!
steve = Person(18, 180, "London")
steve.age = 19
setfield!: immutable struct of type Person cannot be changed
Julia 中级

结构体 - 可变结构体

  • 使用 mutable 关键字创建可变结构体。
mutable struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
steve.age = 19
println(steve)
Person(19, 180, "London")
Julia 中级

结构体 - 带类型的结构体

  • 在结构体定义中可为每个字段指定数据类型。
mutable struct Person
    age::Int64
    height::Int64
    location::String
end
steve = Person(18.5, 180, "London")
InexactError: Int64(18.5)
Julia 中级

Passons à la pratique !

Julia 中级

Preparing Video For Download...