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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号