這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package main import ("fmt""bufio""io""os""flag""strconv")// 定義一個結構體type ReadWrite struct {In *stringOut *string}// 定義初始化方法func (rw *ReadWrite) Init() {rw.In = flag.String("in", "in", "in")rw.Out = flag.String("out", "out", "out")flag.Parse()}// 定義讀檔案的方法func (rw *ReadWrite) Read() (result []int, err error) {file, err1 := os.Open(*(rw.In))if nil != err1 {panic("error to open file...")}defer file.Close()br := bufio.NewReader(file)result = make([]int, 0)for {line, isPrefix, err2 := br.ReadLine()if nil != err2 {if io.EOF == err2 {fmt.Println("finish read ...")}break}if isPrefix {return}str := string(line)value, err3 := strconv.Atoi(str)if nil != err3 {err = err3return}result = append(result, value)}return}// 定義寫檔案的方法func (rw *ReadWrite) Write(value []int) {file, err := os.Create(*(rw.Out))if nil != err {panic("error to create file...")}defer file.Close()for index, res := range value {str := strconv.Itoa(res*index)file.WriteString(str + "\n")}}func main() {defer func() {if ex:=recover();ex!=nil {fmt.Println(ex)}}()rw := new(ReadWrite)rw.Init()value, err := rw.Read()if nil != err {panic("error.....")}rw.Write(value)}