Go Programming Language

1、go run %filename 可以直接编译并运行一个文件,期间不会产生临时文件。例如 main.go。

go run main.go

2、Package

  Go code is organized into packages, which are similar to libraries or modules in other languages. A package consists of one or more .go source files in a single directory that define what the package does.

  The Go standard library has over 100 packages for common tasks like input and output, sorting, and text manipulation. 

  Package main is speci al. It defines a standalone executable program, not a library. Within package main the func tion main is also special—it’s where execution of the program begins.

package main

import "fmt"

func main(){
    fmt.Printf("hello, world\n")
}

 

  A prog ram will not compile if there are missing imports or if there are unnecessary ones. This strict requirement prevents references to unused packages from accumulating as programs evolve.

3、Go does not require semicolons at the end s of statements or declarat ions, except where two or more app ear on the same line.

  In effect, newlines following certain tokens are converted into semicolons, so where newlines following  certain tokens are converted into semicolons.

  token后面跟着换行符会被转换为 semicolon。

4、Go takes a strong stance on code formatting . The gofmt tool rewrites code into the standard format, and the go tool’s fmt subcommand applies gofmt to all the files in the specified package, or the ones in the current directory by default.

  goimports, addition ally manages the insertion and removal of import declarations as needed. It is not part of the standard distribution but you can obtain it with this command:

$ go get golang.org/x/tools/cmd/goimports

5、os.Args

  The os package provides functions and other values for dealing with the operating system in a platform-independent fashion.

  os.Args 可以获取命令行参数。

  os.Args is a slice of strings. a slice as a dynamically sized sequence s of array elements where individual elements can be accessed as s[i] and a contiguous subsequence as s[m:n]. The number of elements is given by len(s). As in most other programming languages, all indexing in Go uses half-open intervals that include the first index but exclude the last, because it simplifies logic. For example, the slice s[m:n], where 0 ≤ m ≤ n ≤ len(s), contains n-m elements.

  If m or n is omitted, it defaults to 0 or len(s) respectively, so we can abbreviate the desired slice as os.Args[1:].

6、echo1 示例

package main

import (
    "fmt"
    "os"
)

func main(){
    var s, sep string
    for i:=1; i<len(os.Args); i++{
        s += sep+os.Args[i]
        sep = ""
    }
    fmt.Println(s)
}

  注意点:

  1)一个 import 可以导入多个 package。

  2)变量类型旋转在变量定义后。

  3)for 语句没有 ()。

  4)The := symbol is part of a short variable declaration, a statement that declares one or more variables and gives them appropriate types based on the initializer values;

    := 定义并且赋予初始值。

7、Go 中只有 i++,没有++i。

8、for循环语法。没有(),以及必须有{}。

  Go Programming Language

  可以没有 initialization、post,如下:

  Go Programming Language

  下面是无穷循环:

  Go Programming Language

9、echo2示例

package main

import (
    "fmt"
    "os"
)

func main(){
    s,sep:="",""
    for _,arg:=range os.Args[1:]{
        s+=sep+arg
        sep=""
    }
    fmt.Println(s)
}

  1)range produces a pair of values: the index and the value of the element at that index.

  2)blank identifier, whose name is _(an underscore).The blank identifier may be used whenever syntax requires a variable name but program logic does not..

  3)several ways to declare a string variable:

    Go Programming Language

  4)上述代码中字符串累加非常的低效,可以使用 strings.Join()方法来优化。

    Go Programming Language

10、dup1示例

  

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main(){
    counts := make(map[string]int)
    input:=bufio.NewScanner(ois.Stdin)
    for input.Scan(){
        counts[input.Text()]++
    }

    for line,n:=range counts{
        if n>1 {
            fmt.Printf("%d\t%s\n", n, line)
        }
    }
}

  1)map[string]int,代表key是string类型,value是int类型。加上make() 用于创建一个此类型的map。

  2)The order of map iteration is not specified, but in practice it is random. This design is intentional, since it prevents programs from relying on any particular ordering where none is guaranteed.

  3)The Scan functino returns true if there is a line and false when there is no more input.

11、dup2 示例

 1 package main
 2 
 3 
 4 import (
 5     "bufio"
 6     "fmt"
 7     "os"
 8 )
 9 
10 func main(){
11     counts :=make(map[string]int)
12     files:=os.Args[1:]
13     if len(files)==0{
14         countLines(os.Stdin, counts)
15     }else{
16         for _,arg:=range files{
17             f,err:=os.Open(arg)
18             if err!=nil{
19                 fmt.Fprintf(os.Stderr, "dup2:%v\n", err)
20                 continue
21             }
22             countLines(f, counts)
23             f.Close()
24         }
25     }
26     for line, n:=range counts{
27         if n>1{
28             fmt.Printf("%d\t%s\n", n, line)
29         }
30     }
31 }
32 
33 func countLines(f *of.File, counts map[string]int){
34     input:=bufio.NewScanner(f)
35     for input.Scan(){
36         counts[input.Text()]++
37     }
38 }
View Code

相关文章: