cgo 从 Go 访问 C struct 字段:下划线还是没有下划线?

cgo C struct field access from Go: underscore or no underscore?

我 运行 在线文档与我在程序中看到的在 GO 代码中访问 C 结构的行为脱节。 go version 说我正在使用:

go version go1.4.2 linux/amd64

根据 GO CGO documentation

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.

我遇到了麻烦,所以制作了一个快速示例程序来测试它:

package main
// struct rec
// {
//      int    i;
//      double d;
//      char*  s;
// };
import "C"
import "fmt"
func main() {
        s := "hello world"
        r := C.struct_rec{}
        r.i = 9
        r.d = 9.876
        r.s = C.CString(s)
        fmt.Printf("\n\tr.i: %d\n\tr.d: %f\n\tr.s: %s\n", 
                r.i, 
                r.d, 
                C.GoString(r.s))
}

当我按照文档指示使用下划线时(例如,用 r._i 代替上面的 r.i),我得到以下编译错误:

r._i undefined (type C.struct_rec has no field or method _i)

当我不使用下划线时它工作正常。我用指针和非指针都试过了。我唯一能想到的另一个想法是,也许是因为我在 GO 而不是 C 中分配了实例,是这样吗??

感谢您的帮助!

答案就在您问题中的引用中:

Within the Go file, C's struct field names that are keywords in Go can be accessed by prefixing them with an underscore(…)

ids 不是 Go 中的关键字。