dsjojts9734 2016-07-22 03:17
浏览 24
已采纳

在Go中实现接口

My project is organized as follows

github.com/achanda/poke
├── cmd
│   └── poke.go
├── scanner.go
├── txt_scanner.go
└── types.go

The files are as follows

# 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
}

Now I am trying to call this in my main package (in poke.go) like this

package main

import "github.com/achanda/poke"

func main() {
    var sr poke.Scanner
    sr = poke.txtScanner{txt}
    sr.Scan()
}

This fails to run with

# command-line-arguments
./poke.go:111: cannot refer to unexported name poke.txtScanner
./poke.go:111: undefined: portscan.txtScanner

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • doujiao1905 2016-07-22 04:13
    关注

    you need to access type or field outside package, so you should export them using first letter upper case:

    first you should define your txtScanner and txt string with first upper case letter, otherwise you will see this error too:

    .\poke.go:8: implicit assignment of unexported field 'txt' in poke.TxtScanner literal
    

    like this:

    type TxtScanner struct {
        Txt string
    }
    

    also see newTxtScanner(host string) function in this working sample codes:
    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”