英文:
How to add a field with a reserved keyword as its name to a structure?
问题
I'm trying to add a field called type
to a V structure used for the C interop. It is failing, because type
is a keyword too.
The original structure in C:
typedef struct some_s {
int type;
} some_t;
The structure declared in V:
#include "some.h"
[typedef]
struct C.some_t {
type int
}
The error when trying to compile the V source:
❯ v some.v
some.v:17:2: error: unexpected keyword `type`, expecting name
15 | [typedef]
16 | struct C.some_t {
17 | type int
| ~~~~
18 | }
Is there a way to mark the type
as a name of a structure field?
英文:
I'm trying to add a field called type
to a V structure used for the C interop. It is failing, because type
is a keyword too.
The original structure in C:
typedef struct some_s {
int type;
} some_t;
The structure declared in V:
#include "some.h"
[typedef]
struct C.some_t {
type int
}
The error when trying to compile the V source:
❯ v some.v
some.v:17:2: error: unexpected keyword `type`, expecting name
15 | [typedef]
16 | struct C.some_t {
17 | type int
| ~~~~
18 | }
Is there a way to mark the type
as a name of a structure field?
答案1
得分: 2
我在Discord for V的聊天中得到了Petr的帮助。非常感谢!
这很简单 - 如果你需要使用一个与现有关键字匹配的标识符,只需在它前面加上@
。
在V中声明的结构现在正确了:
#include "some.h"
[typedef]
struct C.some_t {
@type int
}
关于@
前缀的注释在枚举的文档中被“很好地隐藏”:
枚举字段不能重用保留关键字。然而,保留关键字可以用@进行转义。
英文:
I got help from Petr in the chat at Discord for V. Thanks a lot!
It's simple - if you need to use an identifier, which matches an existing keyword, just prefix it with @
.
The structure declared in V, now properly:
#include "some.h"
[typedef]
struct C.some_t {
@type int
}
The note about the @
prefix is "well hidden" in the documentation of enums:
> Enum fields cannot re-use reserved keywords. However, reserved keywords may be escaped with an @.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论