使用来自不同文件的golang中的接口方法

我method想提供一些接口以使其更容易测试


这是功能


文件A


func readFile(s source) ([]byte, error) {

        p := fs.GetPath()

        file, err := ioutil.ReadFile(p + "/" + s.path + "/" + "rts.yaml")

        if err != nil {

            return yamlFile, fmt.Errorf("erro reading file : %s", err.Error())

        }

        return file, err

    }

现在我为它添加结构


type source struct{

    path string

}

界面readFile是implementing


type fileReader interface {

    readFile(path string) ([]byte, error)

}

现在我需要从另一个文件调用这个函数但是我在执行此操作时遇到错误


档案B


type source struct {

    path string

}



a := source{}


yamlFile, err := readFile(a)

我在这里错过了什么?


守着一只汪
浏览 68回答 1
1回答

LEATH

source导入包含结构的包File A,然后使用该结构初始化变量,然后将变量传递给函数readFile。档案Bimport Aa := A.Source{}因为文件 A 中的结构与文件 B 中的结构source不同。文件 A 的结构正在实现接口,这就是为什么您需要导入源结构然后将其传递给函数的原因。sourcesource一个应该注意的是,要使任何结构或函数可导出,您应该以大写字母开头结构或函数名称。文件A// make struct exportabletype Source struct{    path string}实现了不同于档案Btype source struct{    path string}它没有实现接口。已编辑文件Apackage mainimport (    "fmt"    "io/ioutil"    "os")type Source struct {    Path string}type fileReader interface {    readOneFile() ([]byte, error)}func(s Source) readOneFile() ([]byte, error) {    cwd, err := os.Getwd()    file, err := ioutil.ReadFile(fmt.Sprintf("%s/file.txt", cwd))    if err != nil {        return nil, fmt.Errorf("erro reading file : %s", err.Error())    }    return file, err}档案Bpackage mainimport (    "fmt")func main() {    s := Source{}    data, err := s.readOneFile()    if err != nil {        fmt.Errorf("Error in reading the file")    }    fmt.Println(string(data))}
打开App,查看更多内容
随时随地看视频慕课网APP