Reputation: 795
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 ?
Upvotes: 3
Views: 5353
Reputation: 12675
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))
}
Upvotes: 4