Search…
V by Example
en
V por exemplos
V mit einem Beispiel
V dengan Contoh
通过例子学V语言
例子
section_3
函数
方法
数组
结构体
section_1
section_4
section_2
コード例で学ぶV言語
Changelog
Contributing
Documentation Style Guide
Powered By
GitBook
方法
V没有Class。但是可以为类型定义方法。 方法是一个具有特殊接收器参数的函数, 只有指定类型的接收器才能执行此函数。 接收方在
fn
和方法名之间有自己的参数列表。
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
())
28
println
(
"Bob needs to be 16 to register, but he only is ${bob.age}."
)
29
println
(
alice
.
can_register
())
30
bob
.
has_birthday
()
31
println
(
bob
.
age
)
32
}
Copied!
输出
1
false
2
Bob needs to be 16 to register, but he only is 15.
3
true
4
16
Copied!
上面的代码实现了两种类型为
User
的接收器
u
的方法。 注意,
has\birthday()
方法有一个mut接收器,这是必需的,因为我们要更改它的数据。 V的惯例不是使用诸如
self、this
之类的接收者名字,而是一个短的,最好是一个只有一个字母的名字。
练习
1.为
Person
类型创建一个确定某人是否未成年的方法。 2.创建一个确定
Animal
是否有毛发的方法。
Previous
函数
Next
数组
Last modified
2yr ago
Copy link
Contents
练习