Search…
Struct
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 OOP languages, it can be thought as class but with more restrictions.
1
struct User {
2
name string
3
email string
4
country string
5
}
6
7
fn main() {
8
user := User {
9
name: "V developers"
10
11
country: "Canada"
12
}
13
14
println(user.country)
15
}
Copied!
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.
1
user := User { name: "V developers", email: "[email protected]", country: "Canada" }
Copied!

The & prefix

You can allocate a struct on the heap and get a reference to it by using the & prefix as follows:
1
user := &User{"V developers", "[email protected]", "Canada"}
2
println(user.name)
Copied!
The type of user is &User. It's a reference to User.

Access modifiers

Struct fields are private and immutable by default. Their access modifiers can be changed with pub and mut.
1
struct User {
2
email string
3
}
Copied!
You can define them as private mutable.
1
struct User {
2
email string
3
mut:
4
first_name string
5
last_name string
6
}
Copied!
You can also define them as public immmutable (readonly).
1
struct User {
2
email string
3
mut:
4
first_name string
5
last_name string
6
pub:
7
sin_number int
8
}
Copied!
or as public, but mutable only in the parent module.
1
struct User {
2
email string
3
mut:
4
first_name string
5
last_name string
6
pub:
7
sin_number int
8
pub mut:
9
phone int
10
}
Copied!
or public and mutable both inside and outside parent module.
1
struct User {
2
email string
3
mut:
4
first_name string
5
last_name string
6
pub:
7
sin_number int
8
pub mut:
9
phone int
10
pub mut mut:
11
address_1 string
12
address_2 string
13
city string
14
country string
15
zip string
16
}
Copied!

Exercises

  1. 1.
    Create a struct that stores and displays User information.
  2. 2.
    Create a Point struct that holds x and y field and guard them with private and public.
Last modified 2yr ago