Struct
Last updated
Was this helpful?
Last updated
Was this helpful?
A struct is a composite data type (or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing different variables to be accessed via a single pointer or by the struct declared name which returns the same address.
For people coming from languages, it can be thought as class
but with more restrictions.
Note: Structs are allocated on the stack.
You can use a comma to separate each field when creating a new instance of the struct. It's useful when you want to create a new instance on a single line.
&
prefixYou can allocate a struct on the heap and get a reference to it by using the &
prefix as follows:
The type of user
is &User
. It's a reference to User
.
Struct fields are private
and immutable
by default. Their access modifiers can be changed with pub
and mut
.
You can define them as private mutable
.
You can also define them as public immmutable
(readonly).
or as public
, but mutable
only in the parent module.
or public
and mutable
both inside and outside parent module.
Create a struct that stores and displays User
information.
Create a Point
struct that holds x
and y
field and guard them with private and public.