golang begin

1. install go

2. configure sublime
http://blog.csdn.net/cyxcw1/article/details/10329481

3.io package

1) io.Reader

 1 // io.Reader 接口示例
 2 package main
 3 
 4 import (
 5     "fmt"
 6     "io"
 7     "os"
 8     "strings"
 9 )
10 
11 func main() {
12 FOREND:
13     for {
14         readerMenu()
15 
16         var ch string
17         fmt.Scanln(&ch)
18         var (
19             data []byte
20             err  error
21         )
22         switch strings.ToLower(ch) {
23         case "1":
24             fmt.Println("请输入不多于9个字符,以回车结束:")
25             data, err = ReadFrom(os.Stdin, 11)
26         case "2":
27             file, err := os.Open("D:/src/read.go")
28             if err != nil {
29                 fmt.Println("打开文件 read.go:", err)
30                 continue
31             }
32             data, err = ReadFrom(file, 9)
33             file.Close()
34         case "3":
35             data, err = ReadFrom(strings.NewReader("from string"), 12)
36         case "4":
37             fmt.Println("暂未实现!")
38         case "b":
39             fmt.Println("返回上级菜单!")
40             break FOREND
41         case "q":
42             fmt.Println("程序退出!")
43             os.Exit(0)
44         default:
45             fmt.Println("输入错误!")
46             continue
47         }
48 
49         if err != nil {
50             fmt.Println("数据读取失败,可以试试从其他输入源读取!")
51         } else {
52             fmt.Printf("读取到的数据是:%s
", data)
53         }
54     }
55 }
56 
57 func ReadFrom(reader io.Reader, num int) ([]byte, error) {
58     p := make([]byte, num)
59     n, err := reader.Read(p)
60     if n > 0 {
61         return p[:n], nil
62     }
63     return p, err
64 }
65 
66 func readerMenu() {
67     fmt.Println("")
68     fmt.Println("*******从不同来源读取数据*********")
69     fmt.Println("*******请选择数据源,请输入:*********")
70     fmt.Println("1 表示 标准输入")
71     fmt.Println("2 表示 普通文件")
72     fmt.Println("3 表示 从字符串")
73     fmt.Println("4 表示 从网络")
74     fmt.Println("b 返回上级菜单")
75     fmt.Println("q 退出")
76     fmt.Println("***********************************")
77 }

interface:

C:Gosrcpkgioio.go

 1 // Reader is the interface that wraps the basic Read method.
 2 //
 3 // Read reads up to len(p) bytes into p.  It returns the number of bytes
 4 // read (0 <= n <= len(p)) and any error encountered.  Even if Read
 5 // returns n < len(p), it may use all of p as scratch space during the call.
 6 // If some data is available but not len(p) bytes, Read conventionally
 7 // returns what is available instead of waiting for more.
 8 //
 9 // When Read encounters an error or end-of-file condition after
10 // successfully reading n > 0 bytes, it returns the number of
11 // bytes read.  It may return the (non-nil) error from the same call
12 // or return the error (and n == 0) from a subsequent call.
13 // An instance of this general case is that a Reader returning
14 // a non-zero number of bytes at the end of the input stream may
15 // return either err == EOF or err == nil.  The next Read should
16 // return 0, EOF regardless.
17 //
18 // Callers should always process the n > 0 bytes returned before
19 // considering the error err.  Doing so correctly handles I/O errors
20 // that happen after reading some bytes and also both of the
21 // allowed EOF behaviors.
22 //
23 // Implementations of Read are discouraged from returning a
24 // zero byte count with a nil error, and callers should treat
25 // that situation as a no-op.
26 type Reader interface {
27     Read(p []byte) (n int, err error)
28 }

implements:

C:Gosrcpkgosfile.go

1 // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
2 // standard output, and standard error file descriptors.
3 var (
4     Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
5     Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
6     Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
7 )
 1 // Read reads up to len(b) bytes from the File.
 2 // It returns the number of bytes read and an error, if any.
 3 // EOF is signaled by a zero count with err set to io.EOF.
 4 func (f *File) Read(b []byte) (n int, err error) {
 5     if f == nil {
 6         return 0, ErrInvalid
 7     }
 8     n, e := f.read(b)
 9     if n < 0 {
10         n = 0
11     }
12     if n == 0 && len(b) > 0 && e == nil {
13         return 0, io.EOF
14     }
15     if e != nil {
16         err = &PathError{"read", f.name, e}
17     }
18     return n, err
19 }

C:Gosrcpkgstrings eader.go

package strings

import (
    "errors"
    "io"
    "unicode/utf8"
)

// A Reader implements the io.Reader, io.ReaderAt, io.Seeker, io.WriterTo,
// io.ByteScanner, and io.RuneScanner interfaces by reading
// from a string.
type Reader struct {
    s        string
    i        int // current reading index
    prevRune int // index of previous rune; or < 0
}


func (r *Reader) Read(b []byte) (n int, err error) {
    if len(b) == 0 {
        return 0, nil
    }
    if r.i >= len(r.s) {
        return 0, io.EOF
    }
    n = copy(b, r.s[r.i:])
    r.i += n
    r.prevRune = -1
    return
}

2) io.Writer

interface

 C:Gosrcpkgioio.go

1 // Writer is the interface that wraps the basic Write method.
2 //
3 // Write writes len(p) bytes from p to the underlying data stream.
4 // It returns the number of bytes written from p (0 <= n <= len(p))
5 // and any error encountered that caused the write to stop early.
6 // Write must return a non-nil error if it returns n < len(p).
7 type Writer interface {
8     Write(p []byte) (n int, err error)
9 }

implements

C:Gosrcpkgosfile.go

 1 // Write writes len(b) bytes to the File.
 2 // It returns the number of bytes written and an error, if any.
 3 // Write returns a non-nil error when n != len(b).
 4 func (f *File) Write(b []byte) (n int, err error) {
 5     if f == nil {
 6         return 0, ErrInvalid
 7     }
 8     n, e := f.write(b)
 9     if n < 0 {
10         n = 0
11     }
12 
13     epipecheck(f, e)
14 
15     if e != nil {
16         err = &PathError{"write", f.name, e}
17     }
18     return n, err
19 }

 3) test

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "io"
 6     "os"
 7 )
 8 
 9 func main() {
10     inFile, err := os.Open("d:/src/read.go")
11     if err != nil {
12         fmt.Println("can't open file d:/src/read.go")
13         os.Exit(1)               //???????
14     }
15     defer inFile.Close()
16 
17     outFile, err := os.Create("d:/src/output.txt")
18     if err != nil {
19         fmt.Println("can't create file d:/src/output.txt")
20         os.Exit(1)
21     }
22     defer outFile.Close()
23 
24     for {
25         buf := make([]byte, 20)
26         n, err := inFile.Read(buf)
27         if n == 0 && err == io.EOF {     //???????
28             fmt.Println("Done")
29             return
30         }
31         if err != nil {
32             fmt.Println("error occurs during reading")
33             os.Exit(2)
34         }
35 
36         _, err = outFile.Write(buf[:n])   //????????
37         if err != nil {
38             fmt.Println("error occurs during writing")
39             os.Exit(3)
40         }
41     }
42 
43 }

4. package os,log,  encoding/json

 
 1 // Unmarshal parses the JSON-encoded data and stores the result
 2 // in the value pointed to by v.
 3 //
 4 // Unmarshal uses the inverse of the encodings that
 5 // Marshal uses, allocating maps, slices, and pointers as necessary,
 6 // with the following additional rules:
 7 //
 8 // To unmarshal JSON into a pointer, Unmarshal first handles the case of
 9 // the JSON being the JSON literal null.  In that case, Unmarshal sets
10 // the pointer to nil.  Otherwise, Unmarshal unmarshals the JSON into
11 // the value pointed at by the pointer.  If the pointer is nil, Unmarshal
12 // allocates a new value for it to point to.
13 //
14 // To unmarshal JSON into a struct, Unmarshal matches incoming object
15 // keys to the keys used by Marshal (either the struct field name or its tag),
16 // preferring an exact match but also accepting a case-insensitive match.
17 //
18 // To unmarshal JSON into an interface value,
19 // Unmarshal stores one of these in the interface value:
20 //
21 //    bool, for JSON booleans
22 //    float64, for JSON numbers
23 //    string, for JSON strings
24 //    []interface{}, for JSON arrays
25 //    map[string]interface{}, for JSON objects
26 //    nil for JSON null
27 //
28 // If a JSON value is not appropriate for a given target type,
29 // or if a JSON number overflows the target type, Unmarshal
30 // skips that field and completes the unmarshalling as best it can.
31 // If no more serious errors are encountered, Unmarshal returns
32 // an UnmarshalTypeError describing the earliest such error.
33 //
34 // When unmarshaling quoted strings, invalid UTF-8 or
35 // invalid UTF-16 surrogate pairs are not treated as an error.
36 // Instead, they are replaced by the Unicode replacement
37 // character U+FFFD.
38 //
39 func Unmarshal(data []byte, v interface{}) error {
40     // Check for well-formedness.
41     // Avoids filling out half a data structure
42     // before discovering a JSON syntax error.
43     var d decodeState
44     err := checkValid(data, &d.scan)
45     if err != nil {
46         return err
47     }
48 
49     d.init(data)
50     return d.unmarshal(v)
51 }
52 
53 // Unmarshaler is the interface implemented by objects
54 // that can unmarshal a JSON description of themselves.
55 // The input can be assumed to be a valid encoding of
56 // a JSON value. UnmarshalJSON must copy the JSON data
57 // if it wishes to retain the data after returning.
58 type Unmarshaler interface {
59     UnmarshalJSON([]byte) error
60 }


 
原文地址:https://www.cnblogs.com/harrysun/p/3550208.html