Go无法访问其他文件中的导出数据。

huangapple go评论83阅读模式
英文:

Go can't access exported data in other files

问题

我的项目将这些值导出到不同的文件中:

//messages.go
package types

//从Google Glass和连接的信标获取数据的BeaconMsg
type BeaconMsg struct {
instanceID int
namespaceID int
distance int
}

//beacondata.go
package types

import (
"time"
)

//包含来自眼镜的信标信息的Beacondata
type Beacondata struct {
instanceID int
namespaceID int
distance int
RegisterTime time.Time
}

在另一个文件中,我像这样导入了这些类型:

import (
"glassbackend/types"
)

引发错误的代码:

req := new(types.BeaconMsg)
if err := structFromRequest(req, r); err != nil {
log.Errorf(context, "从请求中提取数据时出错 %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if req.namespaceID == "" || req.instanceID == "" {blab blabl}

但是,这段代码给我抛出了错误"req.namespaceID未定义(无法引用未导出的字段或方法namespaceID)(构建)

请注意,代码req := new(types.BeaconMsg)没有引发任何错误,只有我代码的最后一行。

有人知道发生了什么吗?我在导出方面做错了什么吗?我认为除了对还是错之外,没有其他太多要做的事情了。

英文:

My project exports these values in different files:

//messages.go    
package types
    
    //BeaconMsg with data from google glass and the connected beacons
    type BeaconMsg struct {
    	instanceID  int
    	namespaceID int
    	distance    int
    }

//beacondata.go
package types

import (
	"time"
)

//Beacondata with data from glasses containing beacon information
type Beacondata struct {
	instanceID   int
	namespaceID  int
	distance     int
	RegisterTime time.Time
}

In another file I import the types like this:

import (
	"glassbackend/types"
)

Code that throws the error:

req := new(types.BeaconMsg)
		if err := structFromRequest(req, r); err != nil {
			log.Errorf(context, "error extracting data from request %v", err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if req.namespaceID == "" || req.instanceID == "" {blab blabl}

but then this code throws me the error "req.namespaceID undefined (cannot refer to unexported field or method namespaceID)(build)

Note that the code req := new(types.BeaconMsg) does not cast any error, only the last row of my code.

Does anyone have any idea as to what is happening? Am I doing something wrong with the exports? I don't think there is much else to do either right or wrong?

答案1

得分: 4

你只导出了类型BeaconMsg(类型名称),但字段是未导出的。

如果你想从其他包中访问这些字段,你需要通过将它们的名称以大写字母开头来导出:

type BeaconMsg struct {
    InstanceID  int
    NamespaceID int
    Distance    int
}
英文:

You only exported the type BeaconMsg (the type name), but the fields are unexported.

If you want to access the fields too from other packages, you have to export them by starting their names with a capital letter:

type BeaconMsg struct {
    InstanceID  int
    NamespaceID int
    Distance    int
}

huangapple
  • 本文由 发表于 2017年1月17日 18:32:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/41694776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定