Golang包成员(函数/结构/字段)导出问题

2024-09-04  本文已影响0人  牛奶言兼

学习Golang中,对多文件/多模块的使用时,出现问题:

implicit assignment to unexported field a in struct literal of type

或者在使用函数时,习惯性的对练习函数命名为foobar等:

package demo

import (
    "fmt"
)

func foo() string {
    fmt.Println("demo.foo")
}

但在外部使用该模块demo 时,却找不到函数定义,执行报错:

undefined: demo.foo

但换成结构体

package demo

import (
    "fmt"
)

type MyStruct struct {
   a int
}

func foo() string {
    fmt.Println("demo.foo")
}

外部可以获取到demo.MyStruct但是却拿不到成员字段定义,出现:

implicit assignment to unexported field a in struct literal of type

通过查询得知,Golang中如果要导出标识符(identifier)需要遵循规则:

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode uppercase letter (Unicode character category Lu); and
  2. the identifier is declared in the package block or it is a field name or method name.

All other identifiers are not exported.

至此,问题得到完整可靠解决。

对于刚接触Golang的Coder,建议多阅读The Go Programming Language Specification,每个版本都会有一些约定变化,建议关注Release History - The Go Programming Language (google.cn) 以及时适应版本升级带来的差异。

上一篇 下一篇

猜你喜欢

热点阅读