我有一個名為“DoSomething”的方法。DoSomething 會取二進制源數(shù)據(jù)對其進行操作,并寫出二進制數(shù)據(jù)。DoSomething 需要足夠通用以處理源和目標(biāo)的 []byte 數(shù)組或文件句柄。為了實現(xiàn)這一點,我試圖像這樣聲明方法:func DoSomething(source *io.ReadSeeker, destination *io.WriteSeeker)我已經(jīng)實現(xiàn)了 ReadSeeker 和 WriteSeeker 來處理緩沖區(qū),使用我自己自定義的、必需的方法(如果有一種方法可以自動完成這個,我也很想聽聽)。不幸的是,我似乎無法弄清楚如何從文件句柄創(chuàng)建 io.ReadSeeker 或 io.WriteSeeker。我相當(dāng)確定必須有一些預(yù)先處理好的方法,而不必手動實現(xiàn)它們。這可能嗎?
2 回答

倚天杖
TA貢獻1828條經(jīng)驗 獲得超3個贊
一個文件已經(jīng)實現(xiàn)了這兩個。你可以這樣做:
package main
import (
"fmt"
"io"
"os"
)
func main() {
f, err := os.Open("test.txt")
if err != nil {
fmt.Println(err)
}
defer f.Close()
f2, err := os.Create("test2.txt")
if err != nil {
fmt.Println(err)
}
defer f2.Close()
DoSomething(f, f2)
}
func DoSomething(source io.ReadSeeker, destination io.WriteSeeker) {
io.Copy(destination, source)
}
此外,您不需要將指針傳遞給接口,這使得處理它們變得更加容易。
- 2 回答
- 0 關(guān)注
- 436 瀏覽
添加回答
舉報
0/150
提交
取消