更具體地說:我有 2 個讀者。一個是我從 os.Open("someExistingFile") 得到的,另一個是從 strings.NewReader("hello world") 得到的。其中一個實現了 Name(),另一個沒有。我想讓另一個也實現 Name() (例如返回“”)或(首選)僅在實際參數的類型支持時調用 Name() 。我希望下面的代碼片段清楚地表明了我想要解決的問題。我玩過不同的接收器,即使有反射,但我沒有達到目的......package mainimport ( "io" "os" "strings")func main() { stringReader := strings.NewReader("hello world") fileReader, _ := os.Open("someExistingFile") // error handling omitted fileReader.Name() printFilenameIfReaderIsFile(stringReader) printFilenameIfReaderIsFile(fileReader)}func printFilenameIfReaderIsFile(reader io.Reader) { // here I want to ... // ... either check if this reader is of type os.File and in this case call its Name() method (preferred) // ... or use a custom type instead of io.Reader. // This type's Name() method should return the filename for fileReader and nil for stringReader.}
1 回答

ITMISS
TA貢獻1871條經驗 獲得超8個贊
您正在尋找類型開關控制結構。
你的printFilenameIfReaderIsFile
功能應該看起來像(實際上沒有檢查):
func printFilenameIfReaderIsFile(reader io.Reader) {
? switch f := reader.(type) {
? ? case *os.File:
? ? ? // f is now *os.File (not a os.File!)
? ? ? fmt.Printf("%s\n", f.Name())
? }
}
編輯:不要忘記,os.Open
返回 a*os.File
而不是os.File
?see docs!
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消