本文共 787 字,大约阅读时间需要 2 分钟。
package mainimport ( "io" "strings" "fmt" "os")func ReadFrom(reader io.Reader, num int) ([]byte, error) { p := make([]byte, num) n,err := reader.Read(p) if n > 0 { return p[:n], nil } return p, err}//从字符串读func sampleReadFromString() { data, _ := ReadFrom(strings.NewReader("from string"), 12) fmt.Println(string(data))}//从终端读func sampleReadFromStdin() { fmt.Println("please input from std:") data, _ := ReadFrom(os.Stdin, 11) fmt.Println(string(data))}//从文件读func sampleReadFromFile() { file, _ := os.Open("io操作.go") defer file.Close() data, _ := ReadFrom(file, 9) fmt.Println(string(data))}func main() { sampleReadFromString() sampleReadFromStdin() sampleReadFromFile()}
输出:
转载于:https://blog.51cto.com/5660061/2361204