0

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

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

然后使用Cgo调用

var a *C.pcap_rmtauth

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

请问如何解决?

2个回答

0

已采纳

已经找到答案:

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

2

如果是自己写的,建议直接换个名字,不是个好习惯,如果是用的第三方库,可以参考: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.

撰写答案