我的项目安排如下
github.com/achanda/poke
├── cmd
│ └── poke.go
├── scanner.go
├── txt_scanner.go
└── types.go
文件如下
# cat scanner.go
package poke
type Scanner interface {
Scan() *ScanResult
}
# cat txt_scanner.go
package poke
type txtScanner struct {
txt string
}
func newTxtScanner(host string) Scanner {
return txtScanner{txt}
}
func (tcpcs txtScanner) Scan() *ScanResult {
// do stuff
return &result
}
现在我试图在我的主程序包(poke.go)中调用它,就像这样
package main
import "github.com/achanda/poke"
func main() {
var sr poke.Scanner
sr = poke.txtScanner{txt}
sr.Scan()
}
无法使用
运行# command-line-arguments
./poke.go:111: cannot refer to unexported name poke.txtScanner
./poke.go:111: undefined: portscan.txtScanner
我做错了什么?
答案 0 :(得分:2)
您需要访问包外的类型或字段,因此您应该使用首字母大写导出它们:
首先,您应该使用第一个大写字母来定义txtScanner
和txt string
,否则您也会看到此错误:
.\poke.go:8: implicit assignment of unexported field 'txt' in poke.TxtScanner literal
像这样:
type TxtScanner struct {
Txt string
}
在此工作示例代码中也会看到newTxtScanner(host string)
函数:
poke.go:
package main
import "github.com/achanda/poke"
func main() {
s := "test"
var sr poke.Scanner
sr = poke.TxtScanner{s}
sr.Scan()
}
txt_scanner.go:
package poke
type TxtScanner struct {
Txt string
}
func newTxtScanner(host string) Scanner {
return TxtScanner{host}
}
func (tcpcs TxtScanner) Scan() *ScanResult {
// do stuff
result := ScanResult{}
return &result
}
types.go:
package poke
type ScanResult struct {
}
scanner.go:
package poke
type Scanner interface {
Scan() *ScanResult
}