书籍:The Way To Go,第二部分
Interface
type Shaper interface { Area() float32 } type Square struct { side float32 } func (sq *Square) Area() float32 { return sq.side * sq.side } func main() { sq1 := new(Square) sq1.side = 5 areaIntf := Shaper(sq1) // areaIntf := sq1 fmt.Printf(“%f\n”, areaIntf.Area()) }
r := Rectangle{5, 3} q := &square{5} shapes := []Shaper{r, q} for n, _ := range shapes { fmt.Println("Shape details: ", shapes[n]) fmt.Println("Area is: ", shapes[n].Area()) }
type stockPosition struct { ticker string sharePrice float32 count float32 } func (s stockPosition) getValue() float32 { return s.sharePrice * s.count } type car struct { make string model string price float32 } func (c car) getValue() float32 { return c.price } type valuable interface { getValue() float32 } func showValue(asset valuable) { fmt.Printf(“%f\n”, asset.getValue()) } func main() { var o valuable = stockPosition("GOOG", 577.20, 4) showValue(o) o = car{"BMW", "M3", 66500} showValue(o) }
type File interface { ReadWrite Lock Close() } type ReadWrite interface { Read(b Buffer) bool Write(b Buffer) bool } type Lock interface { Lock() Unlock() }
switch t := areaIntf.(type) { case *Square: ... case *Circle: ... case float32: ... } func classifier(items ...interface{}) { for i, x := range items { switch x.(type) { case bool: ... case int: ... case nil: ... } } } classifier(13, -14.3, “BELGIUM”, nil, false)
type List []int func (l List) Len() int { return len(l) } func (l *List) Append(val int) { *l = append(*l, val) } type Appender interface { Append(int) } type Lener interface { Len() int } func CountInto(a Appender, start, end int) { for i := start; i <= end; i++ { a.Append(i) } } func LongEnough(l Lener) bool { return l.Len()*10 > 42 } func main() { var lst List // A bare value // compiler error: // cannot use lst (type List) as type Appender in function // argument: List does not implement Appender (Append method // requires pointer receiver) // CountInto(lst, 1, 10) if LongEnough(lst) { // VALID: Identical receiver type fmt.Printf(“- lst is long enough”) } plst := new(List) // A pointer value CountInto(plst, 1, 10) // VALID: Identical receiver type if LongEnough(plst) { fmt.Printf(“- plst is long enough”) } }
empty interface type specialString string var whatIsThis specialString = "hello" ... testFunc := func(any interface{}) { switch v := any.(type) { case string: fmt.Prinf("any %v is a string type", v) case specialString: fmt.Printf("a specialString type") ... } } ... var ai AbsInterface // declares method Abs() type SqrInterface interface { Sqr() float } var si SqrInterface pp := new(Point) // implement AbsInterface & SqrInterface var empty interface{} empty = pp; ai = empty.(AbsInterface) si = ai.(SqrInterface) empty = si;
reflect
var x float64 = 3.4 fmt.Println(“type:”, reflect.TypeOf(x)) // type: float64 v := reflect.ValueOf(x) fmt.Println(“value:”, v) // value: <float64 Value> fmt.Println(“type:”, v.Type()) // type: float64 fmt.Println(“kind:”, v.Kind()) // kind: float64 fmt.Println(“value:”, v.Float()) // value: 3.4 fmt.Println(v.Interface()) // 3.4 y := v.Interface().(float64) fmt.Println(y) // 3.4
reflect.ValueOf(x) v = reflect.ValueOf(&x) v. CanSet() v.SetFloat(3.1415) ... t := T{23, "skidoo"} s := reflect.ValueOf(&t).Elem() s.NumField() s.Field(0)
例子节选
for i:= 0; i < 10; i++ { a := rand.Int() fmt.Printf(“%d\n”, a) } for I := 0; i < 5; i++ { r := rand.Int(8) fmt.Printf(“%d\n”, r) } fmt.Println() timens := int64(time.Now().Nanosecond()) rand.Seed(timens) fmt.Printf(“r2.2f\n”, 100*rand.Float32())
func typecheck(..., ..., values ... interface{}) { for _, value := range values { switch v := value.(type) { case int: ... case float: ... case string: ... case bool: ... default: ... } } }
func Fibonacci(n int) (res int) { if n <= 1 { res = 1 } else { res = fibonacci(n-1) + Fibonacci(n-2) } return }
// var r *bytes.Buffer = new(bytes.Buffer) var buffer bytes.Buffer for { if s; ok := getNextString(); ok { buffer.WriteString(s) // append } else { break } } fmt.Print(buffer.String(), “\n”)
// var r *bytes.Buffer = new(bytes.Buffer) var buffer bytes.Buffer for { if s; ok := getNextString(); ok { buffer.WriteString(s) // append } else { break } } fmt.Print(buffer.String(), "\n")
s1 := "hello" c := []byte(s1) c[0]= 'c' s2 := string(c)
type Info struct { mu sync.Mutex // sync.RWMutex Str string } func Update(info *Info) { info.mu.Lock() // info.mu.RLock() //info.Str = new value info.mu.Unlock() // info.mu.RUnlock()/Unlock() }
var once sync.Once onceBody := func() { fmt.Println(“Only once”) } done := make(chan bool) for i := 0; i < 10; i++ { go func() { once.Do(onceBody) done <- true }() } for i := 0; i < 10; i++ { <-done }
Reading and Writing
fmt.Scanln(&input) fmt.Scanf("%s %s", &firstName, &lastName) fmt.Sscanf("56.12 / 5212 / Go", "%f / %d / %s", &f, &i, &s)
var inputReader *bufio.Reader var input string var err error func main() { inputReader = bufio.NewReader(os.Stdin) fmt.Println("Please enter some input: ") input, err = inputReader.ReadString('\n') // '\n' is included!!! if err == nil { fmt.Printf("The input was: %s", input) } } ... switch input { case "Philip\r\n": ... } ... buf := make([]byte, 1024) n, err := inputReader.Read(buf)
// inputFile: *os.File inputFile, inputError := os.Open("input.dat") defer inputFile.Close() inputReader := bufio.NewReader(inputFile) for { inputString, readerError := inputReader.ReadString('\n') ... }
import "io/ioutil" ... inputFile, outputFile := "products.txt", "products_copy.txt" buf, err := ioutil.ReadFile(inputFile) if err != nil { fmt.Fprintf(os.Stderr, "File Error: %s\n", err) } err = ioutil.WriteFile(outputFile, buf, 0x644) if err != nil { panic(err.Error()) }
file, err := os.Open("products2.txt") // separated by space ... var col1, col2, col3 []string for { var v1, v2, v3 string _, err := fmt.Fscanln(file, &v1, &v2, &v3) ... } col1 = append(col1, v1) ...
import "compress/gzip" ... var r *bufio.Reader fi, err := os.Open("MyFile.gz") if err != nil { fmt.Fprintf(...) os.Exit(1) } fz, err := gzip.NewReader(fi) if err != nil { r = bufio.NewReader(fi) } else { r = bufio.NewReader(fz) } for { line, err := r.ReadString('\n') ... } ... import "io" ... src, _ := os.Open(srcName) ... dst, _ := os.OpenFile(...) io.Copy(dst, src)
outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666) outputWriter := bufio.NewWriter(outputFile) outputWriter.WriteString(outputString) outputWriter.Flush()
os.Stdout.WriteString("hello, world\n") f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0) f.WriteString("hello, world in a file\n") // not buffered
reading arguments from the cmd-line
who := "Alice" if len(os.Args) > 1 { who += strings.Join(os.Args[1:], " ") } fmt.Println("Good Morning", who)
import "flag" ... var NewLine = flag.Bool(“n”, false, “print on newline”) ... flag.PrintDefaults() flag.Parse() var s string = "" for i := 0; i < flag.NArg(); i++ { s += flag.Arg(i) if *NewLine { s += "\n" } else { s += " " } } // a.out –n A B C
json dataformat
type Address struct { Type string City string Country string } ... pa := Address{"private", "Aartselaar", "Belgium"} js, _ := json.Marshal(pa) // json.MarshalForHTML(pa) ... file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O...) enc := json.NewEncoder(file) err := enc.Encode(vc)
b = []byte({"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}) var f interface{} err := json.Unmarshal(b, &f) map[string]interface{}{ // f "Name": "Wednesday", "Age": 6 "Parents": []interface{}{ "Gomez", "Morticia", }, }
func Unmarshal(data []byte, v interface{}) type FamilyMember struct { Name string Age int Parents []string } var m FamilyMember err := json.Unmarshal(b, &m)
func NewDecoder(r io.Reader) *Decoder func NewEncoder(w io.Writer) *Encoder func (dec *Decoder) Decode(v interface{}) error
xml dataformat
var t, token xml.Token var err error func main() { input := "<Person><FirstName>Laura</FirstName>" input += "<LastName>Lynn</LastName></Person>" inputReader := strings.NewReader(input) p := xml.NewParser(inputReader) for t, err = p.Token(); err == nil; t, err = p.Token() { switch token := t.(type) { case xml.StartElement: name := token.Name.Local fmt.Printf("Token name: %s\n", name) for _, attr := range token.Attr { attrName := attr.Name.Local attrValue := attr.Value fmt.Printf(“attribute: %s %s\n”, attrName, attrValue) // ... } case xml.EndElement: fmt.Println("End of token") case xml.CharData: content := string([]byte(token)) fmt.Printf("The content: %v\n", content) // ... default: // ... } } }
Cryptography
package hash: adler32, crc32, crc64 and fnv
package crypto: md4, md5, sha1, aes, blowfish, rc4, rsa, xtea
hasher := sha1.New() io.WriteString(hasher, "test") b := []byte{} fmt.Printf("Result: %x\n", hasher.Sum(b)) hasher.Reset() data := []byte("We shall overcome!") n, err := hasher.Write(data) if n != len(data) || err != nil { log.Printf("Hash write error: %v / %v", n, err) } checksum := hasher.Sum(b) fmt.Printf("Result: %x\n", checksum)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。