Search…
Methods
V does not have classes. But one can define methods for types. A method is a function that has a special receiver argument, only a receiver of the specified type can execute this function. The receiver has its own argument list between fn and the method name.
1
struct User {
2
name string
3
email string
4
mut:
5
age int
6
}
7
8
fn (u User) can_register() bool {
9
return u.age > 15
10
}
11
12
fn (u mut User) has_birthday() {
13
u.age += 1
14
}
15
16
fn main() {
17
mut bob := User {
18
name: 'Bob'
19
email: '[email protected].com'
20
age: 15
21
}
22
alice := User {
23
name: 'Alice'
24
email: '[email protected]-mail.com'
25
age: 17
26
}
27
println(bob.can_register()) // false
28
println('Bob needs to be 16 to register, but he only is ${bob.age}.') // Bob needs to be 16 to register, but he only is 15.
29
println(alice.can_register()) // true
30
bob.has_birthday()
31
println(bob.age) // 16
32
}
Copied!
This code above realizes two methods for receivers u of type User. Note that the method has_birthday() has a mut receiver, this is needed here since we want to change its data. The convention of V is not to use receiver names like self, this or similar things but a short, preferably one letter long, name.

Exercises

  1. 1.
    Create a method for the type Person that determines whether a person is underage or not.
  2. 2.
    Create a method that determines whether an Animal has fur or not.
Last modified 2yr ago
Copy link
Contents
Exercises