dongsu1539 2018-10-03 07:10
浏览 514
已采纳

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

I've method which I want to provide some interface to make it more easier to test

This is the function

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

Now I add for it struct

type source struct{
    path string
}

And the interface that the readFile is implementing

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

And now I need to call this function from another file but Im getting error while doing this

File B

type source struct {
    path string
}


a := source{}

yamlFile, err := readFile(a)

what am I missing here ?

  • 写回答

1条回答 默认 最新

  • douhunbei0166 2018-10-03 10:17
    关注

    Import the package containing the source struct in File A and then use that struct to initialize the variable after that pass the variable to the readFile function.

    File B

    import A
    a := A.Source{}
    

    Because source struct in File A is different from source struct in File B. And source struct of File A is implementing the interface that's why you need to import the source struct and then pass it into the function.

    One this should be noticed that to make any struct or function exportable you should start the struct or fucntion name with upper case letter.

    File A

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

    implemented the interface which is different from

    File B

    type source struct{
        path string
    }
    

    which does not implemented the interface.

    Edited

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

    File 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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来