[关闭]
@mSolo 2015-05-07T03:09:19.000000Z 字数 16456 阅读 3610

Golang 自学之路(一)

Go Golang


项目结构范例

  1. bin/
  2. todo # command executable
  3. pkg/
  4. linux_amd64/
  5. code.google.com/p/goauth2/ # reflect your OS and architecture
  6. oauth.a # package object
  7. github.com/nf/todo/ task.a
  8. src/
  9. code.google.com/p/goauth2/
  10. .hg/ # mercurial repository metadata
  11. oauth/
  12. oauth.go # package source
  13. oauth_test.go # test source
  14. github.com/nf/
  15. todo/
  16. .git/
  17. task/
  18. task.go # package source
  19. todo.go

入门:Hello World

  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Printf("hello, world\n")
  5. }

$ go run helloworld.go
$ 6g helloworld.go ---> $ 6l helloworld.6 ---> $ ./6.out

  1. $HOME/HelloWorldWorkspace/
  2. bin/
  3. helloworld
  4. pkg/
  5. src/
  6. github.com/msolo/helloworld
  7. .git
  8. helloworld.go
  9. $ export GOPATH=$HOME/HelloWorldWorkspace
  10. $ go install github.com/msolo/helloworld
  11. $ $GOPATH/bin/helloworld
  12. hello, world

使用包

  1. package newmath
  2. // Sqrt returns an approximation to the square root of x.
  3. func Sqrt(x float64) float64 {
  4. z := 1.0
  5. for i := 0; i < 1000; i++ {
  6. z -= (z*z - x) / (2 * z)
  7. }
  8. return z
  9. }
  1. package main
  2. import (
  3. fm "fmt"
  4. "github.com/user/newmath"
  5. )
  6. func main() {
  7. fm.Printf("Hello, world. Sqrt(2) = %v\n", newmath.Sqrt(2))
  8. }
  1. $ cd $HOME/HelloWorldWorkspace/
  2. bin/
  3. helloworld
  4. pkg/
  5. linux_amd64/
  6. github.com/user/
  7. newmath.a
  8. src/
  9. github.com/user/helloworld
  10. helloworld.go
  11. github.com/user/newmath
  12. sqrt.go

关于 Packages

Godoc 基本使用

  1. $ go get -v code.google.com/p/go.tools/cmd/godoc # 安装
  2. $ godoc -http=:8888 -goroot=$GOROOT # Open http://localhost:8888
  3. $ godoc cmd/go
  4. $ godoc –src fmt Printf

关于注释的要点

  1. 不论编写任何大小的注释,都要记得,第一句话将出现在 godoc 的 package list中。
  2. 紧接着下一行的文本被认为是同一段的;段落必须空出一行来分隔。
  3. 预格式化文本必须在注释符号内缩进
  4. 以”BUG(who)”开头的顶级注释会被识别为已知的bug,会被包含在包文档的”Bugs”部分。”who”应当是能提供更进一步信息的用户的名字。

程序的美化工具:gofmt

使用 Go

01. func : init()

02. 类型与所占内存空间

  1. const str = "str"
  2. var identifier int (= 5)
  3. name := "Jack"
  4. a, b, c := 5, 7, "abc"
  5. type (
  6. IZ int
  7. STR string
  8. )
  9. var a IZ = 5
  10. b := int32(a)
  11. const (
  12. Sunday = iota // Sunday = 0
  13. Monday // 1
  14. ...
  15. )
  16. var (
  17. a int
  18. b bool
  19. )
  20. var (
  21. a = 15
  22. b = false
  23. )

03. 首字母决定可见性规则

04. 基本输出

05. 控制结构

06. 字符串

  1. fmt.Println(strings.ContainsAny("failure", "u & i"))
  2. fmt.Printf("Fields are: %q", strings.Fields(" foo bar baz ")) // ["foo" "bar" "baz"]
  3. s := []string{"foo", "bar", "baz"}
  4. fmt.Println(strings.Join(s, ", ")) // foo, bar, baz
  5. fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1)) // moo moo moo
  6. fmt.Printf("%q\n", strings.Split("a,b,c", ",")) // ["a" "b" "c"]
  7. fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ",")) // ["a," "b," "c"]
  8. fmt.Println(strings.Title("her royal highness")) // Her Royal Highness
  9. fmt.Printf("[%q]", strings.Trim(" !!! Achtung! Achtung! !!! ", "! ")) // ["Achtung! Achtung"]
  10. fmt.Println(strings.TrimSpace(" \t\n a lone gopher \n\t\r\n")) // a lone gopher

07. strconv

  1. func Atoi(s string) (i int, err error)
  2. func Itoa(i int) string
  3. // accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False
  4. func ParseBool(str string) (value bool, err error)
  5. // 解析小数点后6位,不能带其它字符
  6. func ParseFloat(s string, bitSize int) (f float64, err error)
  7. func ParseInt(s string, base int, bitSize int) (i int64, err error)

08. time & date

  1. const (
  2. ANSIC = "Mon Jan _2 15:04:05 2006"
  3. UnixDate = "Mon Jan _2 15:04:05 MST 2006"
  4. RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
  5. RFC822 = "02 Jan 06 15:04 MST"
  6. RFC822Z = "02 Jan 06 15:04 -0700" // with zone
  7. RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
  8. RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
  9. RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700"
  10. RFC3339 = "2006-01-02T15:04:05Z07:00"
  11. RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
  12. Kitchen = "3:04PM"
  13. Stamp = "Jan _2 15:04:05"
  14. StampMilli = "Jan _2 15:04:05.000"
  15. StampMicro = "Jan _2 15:04:05.000000"
  16. StampNano = "Jan _2 15:04:05.000000000"
  17. )
  18. time.Second
  19. time.January
  20. time.Sunday
  21. fmt.Println(t.Format(time.RFC822))
  22. const shortForm = "2006-01-02"
  23. t, _ = time.Parse(shortForm, "2013-Feb-03")
  24. AddDate(-1, 2, 3) applied to 2011-01-01 ---> 2010-03-04
  25. oneday, _ := time.ParseDuration("24h")

09. functions

Built-in function : lencapnewmakecopyappendpanicrecover
defer: a) 多个defer工作方式: 后进先出(LIFO);b) tracing

  1. g := func(i int) { fmt.Printf("%d\n", i) }
  2. type binOp func(int, int) (int, int, int)
  3. someFunc := binOp
  4. func getX2AndX3_2(input int) (x2 int, x3 int) { // 命名返回值
  5. //...
  6. }
  7. func min(a ...int) int { ... }
  8. arr := []int{7, 9, 3, 5, 1}
  9. x := min(arr...) // x := min(7, 9, 3, 5, 1)
  10. func(x, y int) int {
  11. return x + y
  12. }(3, 4)
  13. func main() {
  14. printHeader()
  15. defer printFooter()
  16. }

10. arrays and slices

  1. var arrAge = [5]int{18, 20, 15, 22}
  2. var arrLazy2 = []int{5, 6, 7, 8, 22}
  3. var arrKeyValue1 = [5]string{3: "Chris", 4: "Ron"}
  4. var arrKeyValue2 = []string{3: "Chris", 4: "Ron"}
  5. var slice1 []type = arr1[start:end]
  6. var slice2 []type = arr1[:] // &arr1
  7. // creating a slice with make
  8. var slice1 []type = make([]type, len, cap)
  9. var slice2 []int = make([]int, 10)
  10. // reslicing
  11. s1 = s1[0:len(s1)+1]
  12. // copying and appending slices
  13. s1_from := []int{1, 2, 3}
  14. s1_to := make([]int, 10)
  15. n := copy(s1_to, s1_from) // [1 2 3 0 0 ... 0]
  16. s13 := []int{1, 2, 3}
  17. s13 = append(s13, 4, 5, 6) // [1 2 3 4 5 6]
  18. sort.Ints(arr1)
  19. sort.IntsAreSorted(arr1)
  20. sort.Float64s(arr2)
  21. func SearchStrings(a []string, x string) int
  22. func Strings(a []string) // sorts a slice in increasing order

11. maps

  1. map1 := make(map[string]float)
  2. map2 := map[string]float{}
  3. mf := map[int]func() int {
  4. 1: func() int { return 10 },
  5. 5: func() int { return 50 },
  6. }
  7. delete(map1, key1)

12. regexp

  1. ok, _ := regexp.Match(pat, []byte(searchIn))
  2. ok, _ := regexp.MatchString(pat, searchIn)
  3. // func Compile(expr string) (*Regexp, error)
  4. re := regexp.MustCompile("fo.?")
  5. fmt.Printf("%q\n", re.FindString("seafood")) // "foo"
  6. // func (re *Regexp) Split(s string, n int) []string
  7. s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
  8. searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
  9. pat := "[0-9]+.[0-9]+"
  10. f := func(s string) string {
  11. v, _ := strconv.ParseFloat(s, 32)
  12. return strconv.FormatFloat(v * 2, 'f', 2, 32)
  13. }
  14. re, _ := regexp.Compile(pat)
  15. str1 := re.ReplaceAllString(searchIn, "##.#")
  16. str2 := re.ReplaceAllStringFunc(searchIn, f)

13. structs and methods

  1. type struct1 struct {
  2. i1 int
  3. f1 float32
  4. str string
  5. }
  6. func main() {
  7. ms := new(struct1) // ms := &struct1{10, 15.5, “Chris”}
  8. ms.i1 = 10 // var mt struct1
  9. ms.f1 = 15.5 // mt = struct1{10, 15.5, “Chris”}
  10. ms.str = "Chris"
  11. }
  12. type B struct {
  13. thing int
  14. }
  15. func (b *B) write() string { return fmt.Sprint(b) }
  16. /* -----------------------*
  17. * multiple inheritance *
  18. * -----------------------*/
  19. type camera struct { }
  20. func (c *camera) TakeAPicture() string {
  21. return "click"
  22. }
  23. type phone struct { }
  24. func (p *phone) Call() string {
  25. return "Ring Ring"
  26. }
  27. type cameraPhone struct {
  28. camera
  29. phone
  30. }
  31. cp := new(cameraPhone)
  32. cp.TakeAPicture()
  33. cp.Call()
  1. type TagType struct {
  2. field1 bool "An important answer"
  3. field2 string "The name of the thing"
  4. field3 int "How much there are"
  5. }
  6. func main() {
  7. tt := TagType{true, "Barak Obama", 1}
  8. for i:= 0; i< 3; i++ {
  9. reflectTag(tt, i)
  10. }
  11. }
  12. func reflectTag(tt TagType, ix int) {
  13. ttType := reflect.TypeOf(tt)
  14. ixField := ttType.Field(ix)
  15. fmt.Printf("%v\n", ixField.Tag)
  16. }

进阶

14. interface

interfaces in Go are short, they usually have from 0 ~ 3 methods.

第一部分:基本使用

  1. type Shaper interface {
  2. Area() float32
  3. }
  4. type Square struct {
  5. side float32
  6. }
  7. func (sq *Square) Area() float32 {
  8. return sq.side * sq.side
  9. }
  10. func main() {
  11. sq1 := new(Square)
  12. sq1.side = 5
  13. areaIntf := Shaper(sq1) // areaIntf := sq1
  14. fmt.Printf(“%f\n”, areaIntf.Area())
  15. }
  16. func (r Rectangle) Area() float32 { // type Rectangle struct { length, width float32 }
  17. return r.length * r.width
  18. }
  19. r := Rectangle{5, 3}
  20. q := &square{5}
  21. shapes := []Shaper{r, q}
  22. for n, _ := range shapes {
  23. fmt.Println("Area is: ", shapes[n].Area())
  24. }
  1. type valuable interface {
  2. getValue() float32
  3. }
  4. type stockPosition struct {
  5. ticker string
  6. sharePrice float32
  7. count float32
  8. }
  9. func (s stockPosition) getValue() float32 {
  10. return s.sharePrice * s.count
  11. }
  12. type car struct {
  13. make string
  14. model string
  15. price float32
  16. }
  17. func (c car) getValue() float32 {
  18. return c.price
  19. }
  20. func showValue(asset valuable) {
  21. fmt.Printf(“%f\n”, asset.getValue())
  22. }
  23. func main() {
  24. var o valuable = stockPosition("GOOG", 577.20, 4)
  25. showValue(o)
  26. o = car{"BMW", "M3", 66500}
  27. showValue(o)
  28. }

第二部分:继承

  1. type ReadWrite interface {
  2. Read(b Buffer) bool
  3. Write(b Buffer) bool
  4. }
  5. type Lock interface {
  6. Lock()
  7. Unlock()
  8. }
  9. type File interface {
  10. ReadWrite
  11. Lock
  12. Close()
  13. }

第三部分:关于类型

  1. func classifier(items ...interface{}) {
  2. for i, x := range items {
  3. switch x.(type) {
  4. case bool: ...
  5. case int: ...
  6. case nil: ...
  7. }
  8. }
  9. }
  10. classifier(13, -14.3, BELGIUM”, nil, false)

第四部分:empty interface 与多接口

  1. type specialString string
  2. var whatIsThis specialString = "hello"
  3. testFunc := func(any interface{}) {
  4. switch v := any.(type) {
  5. case string: fmt.Prinf("any %v is a string type", v)
  6. case specialString: fmt.Printf("a specialString type")
  7. //...
  8. }
  9. }
  1. type Appender interface {
  2. Append(int)
  3. }
  4. type Lener interface {
  5. Len() int
  6. }
  7. type List []int
  8. func (l List) Len() int { // Value-receiver method
  9. return len(l)
  10. }
  11. func (l *List) Append(val int) {
  12. *l = append(*l, val)
  13. }
  14. func CountInto(a Appender, start, end int) {
  15. for i := start; i <= end; i++ {
  16. a.Append(i)
  17. }
  18. }
  19. func LongEnough(l Lener) bool {
  20. return l.Len()*10 > 42
  21. }
  22. func main() {
  23. var lst List // A bare value
  24. // compiler error:
  25. // cannot use lst (type List) as type Appender in function
  26. // argument: List does not implement Appender (Append method requires pointer receiver)
  27. // CountInto(lst, 1, 10),
  28. if LongEnough(lst) { // VALID: Identical receiver type
  29. fmt.Printf("- lst is long enough")
  30. }
  31. plst := new(List) // A pointer value
  32. CountInto(plst, 1, 10) // VALID: Identical receiver type
  33. if LongEnough(plst) {
  34. fmt.Printf("- plst is long enough")
  35. }
  36. }
  37. var ai AbsInterface // declares method Abs()
  38. type SqrInterface interface {
  39. Sqr() float32
  40. }
  41. var si SqrInterface
  42. pp := new(Point) // implement AbsInterface & SqrInterface
  43. var empty interface{}
  44. empty = pp; // everything satisfies empty
  45. ai = empty.(AbsInterface)
  46. si = ai.(SqrInterface)

15. reflect

  1. var x float64 = 3.4
  2. fmt.Println("type:", reflect.TypeOf(x)) // type: float64
  3. v := reflect.ValueOf(x)
  4. fmt.Println("value:", v) // value: <float64 Value>
  5. fmt.Println("type:", v.Type()) // type: float64
  6. fmt.Println("kind:", v.Kind()) // kind: float64
  7. fmt.Println("value:", v.Float()) // value: 3.4 <-------------------
  8. fmt.Println(v.Interface()) // 3.4
  9. y := v.Interface().(float64) // <-------------------
  10. fmt.Println(y) // 3.4
  11. reflect.ValueOf(x)
  12. v = reflect.ValueOf(&x)
  13. v.CanSet()
  14. v.SetFloat(3.1415)
  15. t := T{23, "skidoo"}
  16. s := reflect.ValueOf(&t).Elem()
  17. s.NumField()
  18. s.Field(0)

16. 一些示例

random "math/rand"

  1. for i:= 0; i < 10; i++ {
  2. a := rand.Int()
  3. fmt.Printf("%d\n", a)
  4. }
  5. for I := 0; i < 5; i++ {
  6. r := rand.Int(8)
  7. fmt.Printf("%d\n", r)
  8. }
  9. fmt.Println()
  10. timens := int64(time.Now().Nanosecond())
  11. rand.Seed(timens)
  12. fmt.Printf("r2.2f\n", 100*rand.Float32())

recursive

  1. func Fibonacci(n int) (res int) {
  2. if n <= 1 {
  3. res = 1
  4. } else {
  5. res = fibonacci(n-1) + Fibonacci(n-2)
  6. }
  7. return
  8. }

import "bytes"

  1. // var r *bytes.Buffer = new(bytes.Buffer)
  2. var buffer bytes.Buffer
  3. for {
  4. if s; ok := getNextString(); ok {
  5. buffer.WriteString(s) // append
  6. } else {
  7. break
  8. }
  9. }
  10. fmt.Print(buffer.String(), "\n")

change a character in a string

  1. s1 := "hello"
  2. c := []byte(s1)
  3. c[0]= 'c'
  4. s2 := string(c)

17. Reading and Writing

  1. fmt.Scanln(&input)
  2. fmt.Scanf("%s %s", &firstName, &lastName)
  3. fmt.Sscanf(“56.12 / 5212 / Go”, "%f / %d / %s", &f, &i, &s)
  1. var inputReader *bufio.Reader
  2. var input string
  3. var err error
  4. func main() {
  5. inputReader = bufio.NewReader(os.Stdin)
  6. fmt.Println("Please enter some input: ")
  7. input, err = inputReader.ReadString('\n') // '\n' is included!!!
  8. if err == nil {
  9. fmt.Printf("The input was: %s", input)
  10. }
  11. }
  12. switch input { case "Philip\r\n": ... }
  13. buf := make([]byte, 1024) n, err := inputReader.Read(buf)

reading from a file

  1. inputFile, inputError := os.Open("input.dat")
  2. defer inputFile.Close()
  3. inputReader := bufio.NewReader(inputFile)
  4. for {
  5. inputString, readerError := inputReader.ReadString('\n')
  6. // ...
  7. }
  8. import "io/ioutil"
  9. // ...
  10. inputFile, outputFile := "products.txt", "products_copy.txt"
  11. buf, err := ioutil.ReadFile(inputFile)
  12. if err != nil {
  13. fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
  14. }
  15. err = ioutil.WriteFile(outputFile, buf, 0x644)
  16. if err != nil {
  17. panic(err.Error())
  18. }
  19. file, err := os.Open(“products2.txt”) // separated by space
  20. // ...
  21. var col1, col2, col3 []string
  22. for {
  23. var v1, v2, v3 string
  24. _, err := fmt.Fscanln(file, &v1, &v2, &v3)
  25. // ...
  26. }
  27. col1 = append(col1, v1)
  1. import "compress/gzip"
  2. // ...
  3. var r *bufio.Reader
  4. fi, err := os.Open("MyFile.gz")
  5. if err != nil {
  6. fmt.Fprintf(...)
  7. os.Exit(1)
  8. }
  9. fz, err := gzip.NewReader(fi)
  10. if err != nil {
  11. r = bufio.NewReader(fi)
  12. } else {
  13. r = bufio.NewReader(fz)
  14. }
  15. for {
  16. line, err := r.ReadString('\n')
  17. // ...
  18. }
  19. import "io"
  20. // ...
  21. src, _ := os.Open(srcName)
  22. // ...
  23. dst, _ := os.OpenFile(...)
  24. io.Copy(dst, src)
  1. outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)
  2. outputWriter := bufio.NewWriter(outputFile)
  3. outputWriter.WriteString(outputString)
  4. outputWriter.Flush()
  5. os.Stdout.WriteString("hello, world\n")
  6. f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0)
  7. f.WriteString("hello, world in a file\n") // not buffered

18. reading arguments from the cmd-line

  1. who := "Alice"
  2. if len(os.Args) > 1 {
  3. who += strings.Join(os.Args[1:], " ")
  4. }
  5. fmt.Println("Good Morning", who)
  6. import "flag"
  7. //...
  8. var NewLine = flag.Bool(“n”, false, print on newline”)
  9. //...
  10. flag.PrintDefaults()
  11. flag.Parse()
  12. var s string = ""
  13. for i := 0; i < flag.NArg(); i++ {
  14. s += flag.Arg(i)
  15. if *NewLine {
  16. s += "\n"
  17. } else {
  18. s += " "
  19. }
  20. }
  21. $ a.out n A B C

19. json dataformat

  1. type Address struct {
  2. Type string
  3. City string
  4. Country string
  5. }
  6. ...
  7. pa := Address{"private", "Aartselaar", "Belgium"}
  8. js, _ := json.Marshal(pa) // json.MarshalForHTML(pa)
  9. ...
  10. file, _ := os.OpenFile(“vcard.json”, os.O_CREATE|os.O...)
  11. enc := json.NewEncoder(file)
  12. err := enc.Encode(vc)
  13. b = []byte({"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]})
  14. var f interface{}
  15. err := json.Unmarshal(b, &f)
  16. map[string]interface{}{ // f.(map[string]interface{})
  17. "Name": "Wednesday",
  18. "Age": 6
  19. "Parents": []interface{}{
  20. "Gomez",
  21. "Morticia",
  22. },
  23. }
  24. // func Unmarshal(data []byte, v interface{})
  25. type FamilyMember struct {
  26. Name string
  27. Age int
  28. Parents []string
  29. }
  30. var m FamilyMember
  31. err := json.Unmarshal(b, &m)

20. xml dataformat

import "encoding/xml"

  1. var t, token xml.Token
  2. var err error
  3. func main() {
  4. input := "<Person><FirstName>Laura</FirstName>"
  5. input += "<LastName>Lynn</LastName></Person>"
  6. inputReader := strings.NewReader(input)
  7. p := xml.NewParser(inputReader)
  8. for t, err = p.Token(); err == nil; t, err = p.Token() {
  9. switch token := t.(type) {
  10. case xml.StartElement:
  11. name := token.Name.Local
  12. fmt.Printf(“Token name: %s\n”, name)
  13. for _, attr := range token.Attr {
  14. attrName := attr.Name.Local
  15. attrValue := attr.Value
  16. fmt.Printf(“attribute: %s %s\n”, attrName,
  17. attrValue)
  18. // ...
  19. }
  20. case xml.EndElement:
  21. fmt.Println(“End of token”)
  22. case xml.CharData:
  23. content := string([]byte(token))
  24. fmt.Printf(“The content: %v\n”, content)
  25. // ...
  26. default: // ...
  27. }
  28. }
  29. }

21. Cryptography

  1. hasher := sha1.New()
  2. io.WriteString(hasher, test”)
  3. b := []byte{}
  4. fmt.Printf(“Result: %x\n”, hasher.Sum(b))
  5. hasher.Reset()
  6. data := []byte(“We shall overcome!”)
  7. n, err := hasher.Write(data)
  8. if n != len(data) || err != nil {
  9. log.Printf(“Hash write error: %v / %v”, n, err)
  10. }
  11. checksum := hasher.Sum(b)
  12. fmt.Printf(“Result: %x\n”, checksum)

22. Error handling

  1. type error interface {
  2. Error() string
  3. }
  1. var errNotFound error = errors.New(“Not found error”)
  2. err := errors.New(“math square root of negative number”)
  1. type PathError struct {
  2. Op string
  3. Path string
  4. Err error
  5. }
  1. panic(“A severe error occurred: stopping the program!”)
  2. package parse
  3. // import
  4. type ParseError struct {
  5. Index int
  6. Word string
  7. Error err
  8. }
  9. func (e *ParseError) String() string {
  10. return fmt.Sprintf(“...error parsing %q as int”, e.Word)
  11. }
  12. func Parse(input string) (numbers []int, err error) {
  13. defer func() {
  14. if r := recover(); r != nil {
  15. var ok bool
  16. err, ok = r.(error)
  17. if !ok {
  18. err = fmt.Errorf(“pkg: %v”, r)
  19. }
  20. }
  21. }()
  22. fields := strings.Fields(input)
  23. numbers = fields2numbers(fields)
  24. return
  25. }
  26. func fields2numbers(fields []string) (numbers []int) {
  27. if len(fields) == 0 {
  28. panic(“no words to parse”)
  29. }
  30. for idx, field := range fields {
  31. num, err := strconv.Atoi(field)
  32. if err != nil {
  33. panic(&ParseError{idx, field, err})
  34. }
  35. numbers = append(numbers, num)
  36. }
  37. return
  38. }
  1. package main
  2. import (
  3. fmt
  4. “./parse/parse
  5. )
  6. func main() {
  7. var examples = []string{“1 2 3 4 5”, ..., }
  8. for _, ex := range examples {
  9. fmt.Printf(“Parsing %q:\n “, ex)
  10. nums, err := parse.Parse(ex)
  11. if err != nil {
  12. fmt.Println(err)
  13. continue
  14. }
  15. fmt.Println(nums)
  16. }
  17. }

23. Starting an external command or program

  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. "os"
  6. )
  7. func main() {
  8. env := os.Environ()
  9. procAttr := &os.ProcAttr{
  10. Env: env,
  11. Files: []*os.File{
  12. os.Stdin,
  13. os.Stdout,
  14. os.Stderr,
  15. },
  16. }
  17. pid, err := os.StartProcess(“/bin/ls”, []string{“ls”, “-l”}, procAttr)
  18. if err != nil {
  19. fmt.Printf(“Error %v starting process!”, err) //
  20. os.Exit(1)
  21. }
  22. fmt.Printf(“The process id is %v”, pid)
  23. }
  1. cmd := exec.Command(“gedit”) // this opens a gedit-window
  2. err := cmd.Run()
  3. if err != nil {
  4. fmt.Printf(“Error %v executing command!”, err)
  5. os.Exit(1)
  6. }
  7. fmt.Printf(“The command is %v”, cmd)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注