注解(attribute)

V语言可以针对结构体,结构体字段,函数/方法进行注解

注解的格式统一是:[注解名] 或 [注解名:注解扩展内容]

编译器内置注解

结构体注解

结构体注解统一放在结构体定义前

  • [typedef]

参考:结构体章节 - [heap]

参考:结构体章节

结构体字段注解

结构体字段注解统一放在字段定义后

  • [required]

参考:结构体章节-字段注解 - [json]

参考:json章节 - [skip]

参考:json章节 - [row]

参考:json章节

函数注解

函数注解统一放在函数定义之前

  • [deprecated]

参考:函数章节 - [inline]

参考:函数章节 - [live]

参考:函数章节 - [unsafe]

参考:unsafe章节 - [trusted]

参考:unsafe章节 - [if debug]

这个注解表示该函数只有在编译时加上了-d 调试模式的时候,才会被编译生成,并且可以调用

1. [if debug] 2. fn foo() { 3. } - [windows_stdcall]

这个注解只能用于Win32 API,如果需要传递回调函数的时候使用

1. [windows_stdcall] 2. fn C.DefWindowProc(hwnd int, msg int, lparam int, wparam int) - [console]

这个注解只能用在main函数前,导入了图形库模块(比如gg,ui)后,命令行窗口就不再显示了,查看不到命令行输出,加上这个注解,命令行窗口就会出现

1. [console] 2. fn main() {}

自定义注解

实际上除了编译器内置的注解外,结构体,函数,枚举的定义者可以增加各种自定义注解,然后自己解析,自己使用

注解的扩展性还是比较灵活的

目前结构体注解和结构体字段注解,已经可以通过$for编译时反射来获取所有的注解内容,具体内容可以参考:编译时反射章节

1. [testing]
2. struct StructAttrTest {
3. foo string [attr1;required] //结构体字段自定义注解
4. bar int [attr1; attr2; required]
5. }

7. [testing]
8. struct PubStructAttrTest {
9. foo string
10. bar int
11. }

13. [testing]
14. enum EnumAttrTest {
15. one
16. two
17. }

19. [testing]
20. enum PubEnumAttrTest {
21. one
22. two
23. }

25. [attrone]
26. [attrtwo] //可以同时有多个注解
27. enum EnumMultiAttrTest {
28. one
29. two
30. }

32. [attr1;attr2] //在同一个注解中括号内,注解用分号来区隔
33. fn fn_attribute() {
34. }

36. [testing]
37. fn pub_fn_attribute() {
38. }

40. [attrone]
41. [attrtwo]
42. fn fn_multi_attribute() {
43. }

45. [attrone]
46. [attrtwo]
47. fn fn_multi_attribute_single() {
48. }