go - 使用来自不同文件的golang中的接口(interface)方法

标签 go struct interface

我有方法,我想提供一些接口(interface)使其更容易测试

这是函数

文件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 正在实现的接口(interface)

type fileReader interface {
    readFile(path string) ([]byte, error)
}

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

文件B

type source struct {
    path string
}


a := source{}

yamlFile, err := readFile(a)

我在这里错过了什么?

最佳答案

File A 中导入包含 source 结构的包,然后使用该结构初始化变量,然后将变量传递给 readFile 功能。

文件B

import A
a := A.Source{}

因为文件 A 中的 source 结构与文件 B 中的 source 结构不同。文件 A 的 source 结构实现了接口(interface)为什么需要导入源结构,然后将其传递给函数。

需要注意的是,要使任何结构或函数可导出,您应该以大写字母开头结构或函数名称。

文件A

// make struct exportable
type Source struct{
    path string
}

实现了不同于

的接口(interface)

文件B

type source struct{
    path string
}

没有实现接口(interface)。

已编辑

文件A

package main

import (
    "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
}

文件B

package main

import (
    "fmt"
)

func main() {
    s := Source{}
    data, err := s.readOneFile()
    if err != nil {
        fmt.Errorf("Error in reading the file")
    }
    fmt.Println(string(data))
}

关于go - 使用来自不同文件的golang中的接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52621577/

相关文章:

bash - 从 golang 代码重新加载或获取/etc/enviornment 文件

go - 编译错误只构建一个模块,而不是主包

c - 释放指向其他结构的结构中的指针

c# - 实现接口(interface) C#

java - 枚举与枚举的区别

unit-testing - 何时使用 httptest.Server 和 httptest.ResponseRecorder

database - golang 数据库更新一个不存在的条目

struct - 高语 : Variable length array in struct for use with binary read

object - Go:结构中的方法和方法的 slice

java - Java Class.forName 的问题