Golang 中的“潜规则”

前端之家收集整理的这篇文章主要介绍了Golang 中的“潜规则”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  • GO语言中要提供给外面访问的方法或是结构体必须是首字母大写

在一个公共的头文件中定义了一个结构体,如下所示:

type Header struct {
    ver       int
    magic_num int
    len       int
}

在另一个执行文件中,进行了初始化和赋值:

        var head comm.Header;
        head.ver = 1
        head.magic_num = 0xffee
        head.len = 0

编译时报错

./example_struct2binary.go:21: head.ver undefined (cannot refer to unexported field or method ver)

./example_struct2binary.go:22: head.magic_num undefined (cannot refer to unexported field or method magic_num)

./example_struct2binary.go:23: head.len undefined (cannot refer to unexported field or method len)

后来想起,GO语言中要提供给外面访问的方法或是结构体必须是首字母大写。这个结构体只有结构体名大写了,而里面的字段没有首字母大写,而GO语言在模板调用时应该认为是两个不同的过程,所以找不到值。于是把结构体中字段首字母改为大写后解决

原文链接:https://www.f2er.com/go/189613.html

猜你在找的Go相关文章