Cgo 中 使用 C的struct 出现type关键字,报错

在Go中使用CGO调用第三方C库,出现如下C语言的struct

struct pcap_rmtauth
{
    int type;
    char *username;
    char *password;
};

然后使用Cgo调用

var a *C.pcap_rmtauth

a.type // 此处会报错,因为type是Go中的关键字

请问如何解决?

阅读 6.8k
2 个回答

已经找到答案:

如果C的struct的字段类型是Go的关键字,如 type , 那么在Go代码中可以在字段前加关键字如 x._type

如果是自己写的,建议直接换个名字,不是个好习惯,如果是用的第三方库,可以参考:https://golang.org/src/cmd/cg...

Within the Go file, C's struct field names that are keywords in Go
can be accessed by prefixing them with an underscore: if x points at a C struct with a field named "type", x._type accesses the field.
C struct fields that cannot be expressed in Go, such as bit fields
or misaligned data, are omitted in the Go struct, replaced by
appropriate padding to reach the next field or the end of the struct.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题