Structs
Aggregate types with reference semantics, and how they differ from classes.
A struct is a product type: a fixed set of named fields, declared up front.
struct Point {
var x: int
var y: int
}
fn main() {
let p = Point(3, 4)
println("x={p.x} y={p.y}")
}
Construction is positional
A struct with no constructor of its own gets an implicit one that takes every
field, in declaration order, and stores them. That is how a struct is built.
struct Rect {
var w: float
var h: float
}
fn main() {
let r = Rect(2.0, 3.0)
println(r.w * r.h)
}
You cannot write your own constructor
Declaring one parses and type-checks, but assigning to a field inside a struct constructor fails when the code is generated:
struct Point {
var x: int
var y: int
constructor(x: int, y: int) {
this.x = x // codegen: no inferred type available for this expression
}
}
Field assignments in a user constructor need an explicit type on the right-hand side. Omit the constructor and let the implicit one run; assign fields after construction if you need to change them.
struct Point {
var x: int
var y: int
}
fn main() {
var p = Point(0, 0)
p.x = 3
p.y = 4
println("x={p.x} y={p.y}")
}
Fields are mutable
var fields can be reassigned, because the struct is a reference:
struct Counter {
var n: int
}
fn bump(c: Counter) {
c.n = c.n + 1
}
fn main() {
let c = Counter(0)
bump(c)
bump(c)
println(c.n) // 2
}
Use let fields for a struct you do not want changed, assigning to a let
field is a compile error.
Reference semantics
Like classes, structs are passed by reference. A function that changes a field of its argument changes the caller's copy too.
struct Point {
var x: int
var y: int
}
fn moveTo(p: Point, x: int, y: int) {
p.x = x
p.y = y
}
fn main() {
let p = Point(0, 0)
moveTo(p, 5, 6)
println("p is {p.x},{p.y}") // p is 5,6
}
There is no structural equality
== on a struct compares identity, not fields. Two separately constructed
structs with the same values are not equal:
struct Point {
var x: int
var y: int
}
fn main() {
let a = Point(1, 2)
let b = Point(1, 2)
println(a == b) // false
println(a.x == b.x) // true
}
If you need value semantics, compare the fields you care about:
struct Point {
var x: int
var y: int
}
fn same(p: Point, q: Point) -> bool {
return p.x == q.x && p.y == q.y
}
fn main() {
let a = Point(1, 2)
let b = Point(1, 2)
println(same(a, b)) // true
}
Struct or class?
struct |
class |
|
|---|---|---|
| User constructor | no, use the implicit positional one | yes |
| Inheritance | no | yes, one base class |
| Implements interfaces | no | yes |
is / as |
no | yes |
Use a struct for a fixed record of data. Use a class when you need a constructor, a base class, or an interface.
