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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器