1 回答

TA貢獻1936條經驗 獲得超7個贊
source導入包含結構的包File A,然后使用該結構初始化變量,然后將變量傳遞給函數readFile。
檔案B
import A
a := A.Source{}
因為文件 A 中的結構與文件 B 中的結構source不同。文件 A 的結構正在實現接口,這就是為什么您需要導入源結構然后將其傳遞給函數的原因。sourcesource
一個應該注意的是,要使任何結構或函數可導出,您應該以大寫字母開頭結構或函數名稱。
文件A
// make struct exportable
type Source struct{
path string
}
實現了不同于
檔案B
type source struct{
path string
}
它沒有實現接口。
已編輯
文件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))
}
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報