如何向结构体添加一个以保留关键字命名的字段?

huangapple go评论52阅读模式
英文:

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 @.

huangapple
  • 本文由 发表于 2023年5月21日 06:59:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定