vlang

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?


Solution

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