Go Programming Language

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

  1. 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.

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

  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:

  1. $ 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 示例

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "os"
  6. )
  7.  
  8. func main(){
  9. var s, sep string
  10. for i:=; i<len(os.Args); i++{
  11. s += sep+os.Args[i]
  12. sep = ""
  13. }
  14. fmt.Println(s)
  15. }

  注意点:

  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循环语法。没有(),以及必须有{}。

  

  可以没有 initialization、post,如下:

  

  下面是无穷循环:

  

9、echo2示例

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "os"
  6. )
  7.  
  8. func main(){
  9. s,sep:="",""
  10. for _,arg:=range os.Args[:]{
  11. s+=sep+arg
  12. sep=""
  13. }
  14. fmt.Println(s)
  15. }

  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:

    

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

    

10、dup1示例

  

  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "fmt"
  6. "os"
  7. )
  8.  
  9. func main(){
  10. counts := make(map[string]int)
  11. input:=bufio.NewScanner(ois.Stdin)
  12. for input.Scan(){
  13. counts[input.Text()]++
  14. }
  15.  
  16. for line,n:=range counts{
  17. if n> {
  18. fmt.Printf("%d\t%s\n", n, line)
  19. }
  20. }
  21. }

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

  1)函数调用可以放置函数定义前。本例中 countLines()函数,比C++强。

  2)fmt.Fprintf()函数类似于C++中的fprint。

12、lissajous 示例

  1. package main
  2.  
  3. import(
  4. "image"
  5. "image/color"
  6. "image/gif"
  7. "io"
  8. "math"
  9. "math/rand"
  10. "os"
  11. )
  12.  
  13. var palette = []color.Color{color.White, color.Black}
  14.  
  15. const (
  16. whiteIndex =
  17. blackIndex =
  18. )
  19.  
  20. func main(){
  21. const(
  22. cycles =
  23. res = 0.001
  24. size =
  25. nframes =
  26. delay =
  27. )
  28.  
  29. freq:=rand.Float64()*3.0
  30. anim:=gif.GIF{LoopCount:nframes}
  31. phase:=0.0
  32. for i:=;i<nframes;i++{
  33. rect:=image.Rect(,,*size+,*size+)
  34. img:=image.NewPaletted(rect,palette)
  35. for t:=;t<cycles**math.Pi;t+=res{
  36. x:=math.Sin(t)
  37. y:=math.Sin(t*freq+phase)
  38. img.SetColorIndex(size+int(x*size+0.5),size+int(y*size+0.5),
  39. blackIndex)
  40. }
  41. phase+=0.1
  42. anim.Delay = append(anim.Delay, delay)
  43. anim.Image = append(anim.Image, img);
  44. }
  45. }

  1)import "image/gif",通过 gif 就能直接引用。

  2)const (),the valu of const must be a number, string or boolean.

13、fetch示例

  1. package main
  2.  
  3. import(
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. )
  9.  
  10. func main(){
  11. for _, url:=range os.Args[:]{
  12. resp, err := http.Get(url)
  13. if err!=nil{
  14. fmt.Fprintf(os.Stderr, "fetch:%v\n", err)
  15. os.Exit()
  16. }
  17.  
  18. b,err:=ioutil.ReadAll(resp.Body)
  19. resp.Body.Close()
  20. if err!=nil{
  21. fmt.Fprintf(os.Stderr, "fetch:reading %s:%v\n", url, err)
  22. os.Exit()
  23. }
  24. fmt.Printf("%s", b)
  25. }
  26. }

  1)net/http,其中的 http.Get() 方法可以用于发起一个Http请求,并返回内容。

14、fetch all 示例

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "time"
  10. )
  11.  
  12. func main(){
  13. start :=time.Now()
  14. ch:=make(chan string)
  15. for _,url :=range os.Args[:]{
  16. go fetch(url, ch) // start a goroutine
  17. }
  18.  
  19. for range os.Args[:]{
  20. fmt.Println(<-ch) // receive from channel ch
  21. }
  22.  
  23. fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
  24. }
  25.  
  26. func fetch(url string, ch chan<- string){
  27. start:=time.Now()
  28. resp, err:=http.Get(url)
  29. if err!=nil{
  30. ch<-fmt.Sprint(err) // send to channel ch
  31. return
  32. }
  33.  
  34. nbytes, err:=io.Copy(ioutil.Discard, resp.Body)
  35. resp.Body.Close()
  36. if err!=nil{
  37. ch<-fmt.Sprintf("while reading %s:%v", url, err)
  38. return
  39. }
  40. secs:=time.Since(start).Seconds()
  41. ch<-fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
  42. }

  1)A goroutine is a concurrent function execution. A channel is a communication mechanism that allows one goroutine to pass values of a specified typ e to another goroutine. The function main runs in a goroutine and the go st atement cre ates addition al goroutines.

  2)通过  ch:=make(chan string) 创建一个channel,通过 ch <- str 向 ch中写入内容,通过 <-ch 从ch中读取内容

  3)通过 go func(),创建一个新 goroutine

15、server1示例,使用内置的http package,创建一个 http服务器。

  1. package main
  2.  
  3. import(
  4. "fmt"
  5. "log"
  6. "net/http"
  7. )
  8.  
  9. func main(){
  10. http.HandleFunc("/", handle)
  11. log.Fatal(http.ListenAndserve("localhost:8000", nil))
  12. }
  13.  
  14. func handler(w httpResponseWritter, r *http.Request){
  15. fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
  16. }

  1)http.ListenAndServer(port) 开启Http服务,http.HandleFunc(path, func)设置路由。

  2)http.Request 代表一个请求。

16、server2 示例,通过请求 /count 路径,获得 / 路径的调用次数。

  1. package main
  2.  
  3. import(
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "sync"
  8. )
  9.  
  10. var mu sync.Mutex
  11. var count int
  12.  
  13. func main(){
  14. http.HandleFunc("/", handler)
  15. http.HandleFunc("/count", counter)
  16. log.Fatal(http.ListenAndServe("localhost:8000", nil))
  17. }
  18.  
  19. func handler(w http.ResponseWritter, r *http.Request){
  20. mu.Lock()
  21. count++
  22. mu.Unlock()
  23. fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
  24. }
  25.  
  26. func counter(w http.ResponseWritter, r *http.Request){
  27. mu.Lock()
  28. fmt.Fprintf(w, "Count %d\n", count)
  29. mu.Unlock()
  30. }

  1)import "sync",  var mu sync.Mutex 用于定义一个互斥锁。

  2)A handler pattern that ends with a slash matches any URL that has the pattern as a prefix.

17、server3 示例,用于解析 http 请求 Header & FormData。

  1. func handler(w http.ResponseWritter, r *http.Request){
  2. fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
  3. for k,v:=range r.Header{
  4. fmt.Fprintf(w, "Header[%q] = %q\n", k,v)
  5. }
  6.  
  7. fmt.Fprintf(w, "Host = %q\n", r.Host)
  8. fmt.Fprintf(w, "RemoteAddr=%q\n", r.RemoteAddr)
  9. if err:=r.ParseForm(); err!=nil{
  10. log.Printf(err)
  11. }
  12. for k,v:=range r.Form{
  13. fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
  14. }
  15. }

  1)使用 http.Request.Form 前需要先调用和 http.Request.ParseForm。

  2)在前例中,range 用于获取 [index,value],而本例中 range 用于获取 [key,value]。

  3)if 的条件中可以使用多条语句。下述写法,将 err 的 scope 限制在了 if 语句内。

  1. if err:=r.ParseForm(); err!=nil{
  2. log.Printf(err)
  3. }

  4)

18、Named Types

  

19、Point ers are explicitly visible. The operator yields the address of a variable, and the operator retrieves the variable that the pointer refers to, but there is no point er arithmetic.

20、If an entity is declare d within a function, it is local to that function. If declared outside of a function, however, it is visible in all files of the package to which it belongs.

  函数外定义的变量,事个package中所有的file都可以访问。

  package-level entity is visible not only throughout the source file that contains its declaration, but throughout all the files of the package.

21、The case of the first letter of a name determines its visibility across package boundaries.

  If the name begins with an upper-case letter, it is exported, which means that it is visible and accessible outside of its own package and may be refer red to by other par ts of the program, as wit h Printf in the fmt package.

  如果变量以大写字母开头,则它可以被包外代码引用。

  Package names themselves are always in lower case. 包名永远是小写。

22、variables. Either the type or the  = expression part may be omitted, but not both.

  

  Omitt ing the typ e allows decl arat ion of multiple var iables of different types:

  

23、in Go there is no such thing as an uninitialize d variable.

24、一个函数可以返回多个返回值。

  

25、short variable declaration.

  

  

  multiple variables may be declared and initialized in the same short variable declaration。

  

  短变量声明的左边必须包含至少一个新变量,下左图是ok的,而下右图则会编译错误。

    

  := 只对同一语法块中的变量起 assignment 作用,语法块以外的同名变量会被 ignored。

26、Pointer

  Not every value has an address, but every variable does.

    

  It is perfectly safe for a function to return the address of a local variable !!! Each call of f returns a distinct value.

    

27、flag package 示例

  1. package main
  2.  
  3. import(
  4. "flag"
  5. "fmt"
  6. "strings"
  7. )
  8.  
  9. var n = flag.Bool("n", false, "omit trailing newline")
  10. var sep = flag.String("s", "", "separator")
  11.  
  12. func main(){
  13. flag.Parse()
  14. fmt.Print(strings.Join(flag.Args(), *sep))
  15. if !*n {
  16. fmt.Println()
  17. }
  18. }

  1)flag.Parse() 必须最先调用,默认带有 -h -help的解释。

28、new Function()

  The expression new(T) creates an unnamed variable of type T, initializes it to the zero value of T, and returns its address, which is a value of type *T.

  

  A variable created with new is no different from an ordinary local variable whose address is taken, Thus new is only a syntactic convenience, not a fundamental notion.

  The two newInt functions below have identical behaviors.

    

29、Lifetime of Variables

  The lifetime of a package-level variable is the entire execution of the program.

  By contrast, local variables have dynamic lifetimes: a new instance is create d each time the declaration statement is executed, and the variable lives on until it becomes unreachable, at which point its storage may be rec ycled.

  A compiler may choose to allocate local variables on the heap or on the stack but, perhaps surprisingly, this choice is not determined by whether var or new was used to declare the variable.

  变量分配在堆上还是栈上,由编译器决定, var、new无法对此产生影响。

    

30、Tuple Assignment

  

31、Type Declarations

  

  可以为自定义类型添加Method。

  

  Many types declare a String method of this form because it controls how values of the type appear when printed as a string by the fmt package.

  

32、Packages and Files

  Extensive doc comments are often placed in a file of their own, conventionally called go.doc.

  use the golang.org/x/tools/cmd/goimports tool, which automatically inserts and removes packages from the import declaration as necessary ; most editors can be configured to run goimports each time you save a file. Like the gofmt to ol, it also pretty-prints Go source files in the canonical format.

33、Package Initialization

  Any file may contain any number of functions whose declaration is just:

  

  init functions are automatically executed when the program starts, in the order in which they are declared.

  一个文件可以包含多个 init() 函数,在执行main()前,会按照声明的顺序依次调用。

34、不同的 lexical block 可以定义同名变量。 Inner lexical 优先级高于 Outer Lexical。

  

35、if scope

  

  The second if statement is nested within the first, so variables declared within the first statement's initializer are visible within the second.

  if 中的变量作用范围限定在 if语句中,所以以下代码中对 f 的引用会引起编译错误。

  

  为了解决上述问题,可以像下面这样写代码(但不推荐):

  

36、short variable declaration 要点

  下述代码中, 函数内会新创建一个 local cwd,导致 global cwd 未被初始化。

  

  一种解决方法是,使用 assignment,而不是使用 short variable declaration:

  

37、

38、

39、

40、

Go Programming Language的更多相关文章

  1. iOS Swift-元组tuples(The Swift Programming Language)

    iOS Swift-元组tuples(The Swift Programming Language) 什么是元组? 元组(tuples)是把多个值组合成一个复合值,元组内的值可以使任意类型,并不要求是 ...

  2. iOS Swift-控制流(The Swift Programming Language)

    iOS Swift-控制流(The Swift Programming Language) for-in 在Swift中for循环我们可以省略传统oc笨拙的条件和循环变量的括号,但是语句体的大括号使我 ...

  3. iOS Swift-简单值(The Swift Programming Language)

    iOS Swift-简单值(The Swift Programming Language) 常量的声明:let 在不指定类型的情况下声明的类型和所初始化的类型相同. //没有指定类型,但是初始化的值为 ...

  4. Java Programming Language Enhancements

    引用:Java Programming Language Enhancements Java Programming Language Enhancements Enhancements in Jav ...

  5. The Swift Programming Language 英文原版官方文档下载

    The Swift Programming Language 英文原版官方文档下载 今天Apple公司发布了新的编程语言Swift(雨燕)将逐步代替Objective-C语言,大家肯定想学习这个语言, ...

  6. The Swift Programming Language 中文翻译版(个人翻新随时跟新)

    The Swift Programming Language --lkvt 本人在2014年6月3日(北京时间)凌晨起来通过网络观看2014年WWDC 苹果公司的发布会有iOS8以及OS X 10.1 ...

  7. [iOS翻译]《The Swift Programming Language》系列:Welcome to Swift-01

    注:CocoaChina翻译小组已着手此书及相关资料的翻译,楼主也加入了,多人协作后的完整译本将很快让大家看到. 翻译群:291864979,想加入的同学请进此群哦.(本系列不再更新,但协作翻译的进度 ...

  8. Questions that are independent of programming language. These questions are typically more abstract than other categories.

    Questions that are independent of programming language.  These questions are typically more abstract ...

  9. What is the Best Programming Language to Learn in 2014?

    It’s been a year since I revealed the best languages to learn in 2013. Once again, I’ve examined the ...

  10. C: Answers to “The C programming language, Edition 2”

    <The C programming language> Edition 2的习题答案地址: http://users.powernet.co.uk/eton/kandr2/index.h ...

随机推荐

  1. 【2019.7.16 NOIP模拟赛 T1】洗牌(shuffle)(找环)

    找环 考虑每次洗牌其实是一次置换的过程,而这样必然就会有循环出现. 因此我们直接通过枚举找出每一个循环,询问时只要找到环上对应的位置就可以了. 貌似比我比赛时被卡成\(30\)分的倍增简单多了? 代码 ...

  2. 【2019.7.15 NOIP模拟赛 T2】与非树(nand)(树形DP)

    树形\(DP\) 实际上,这道题应该不是很难. 我们设\(f_{x,i,j}\)表示在以\(x\)为根的子树内,原本应输出\(i\),结果输出了\(j\)的情况数. 转移时,为了方便,我们先考虑与,再 ...

  3. koa2+mysql+vue实现用户注册、登录、token验证

    说明: node.js提供接口,vue展现页面,前后端分离,出于编辑器功能和编辑习惯,vue用HbuilderX,node.js用VScode.(PS:仅作为学习笔记,如有不当之处欢迎指出,在此先谢为 ...

  4. 如何编写一个Systemd Service(转)

    转自 https://segmentfault.com/a/1190000014740871 0x01 什么是Systemd Service Systemd 服务是一种以 .service 结尾的单元 ...

  5. C# HTTP系列6 HttpWebResponse.StatusCode 响应代码中文详解

    系列目录     [已更新最新开发文章,点击查看详细] 1xx - 信息提示 这些状态代码表示临时的响应.客户端在收到常规响应之前,应准备接收一个或多个 1xx 响应 · 100 - Continue ...

  6. SQLAIchemy 学习(一)Session 相关

    0. 前言 最近是使用 SQLAlchemy 框架作为一个 ORM 框架,现对其做简单整理 1. 创建 Session 说到数据库,就离不开 Session.Session 的主要目的是建立与数据库的 ...

  7. SpringBoot第四篇:整合JDBCTemplate

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10868954.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   前面几篇文 ...

  8. sublime-text-3-build-3207 破解+注册码

    按照以下步骤依次进行 打开 https://hexed.it/ 单机 "Open file" 并选择 "sublime_text.exe" 可执行文件. 转到 ...

  9. MySQL的统计总数count(*)与count(id)或count(字段)的之间的各自效率性能对比

    执行效果: 1.  count(1) and count(*) 当表的数据量大些时,对表作分析之后,使用count(1)还要比使用count(*)用时多了!  从执行计划来看,count(1)和cou ...

  10. 『kamp 树形dp』

    kamp Description jz 市的云台山是个很美丽的景区,小 x 暑期到云台山打工,他的任务是开景区的大巴. 云台山景区有 N 个景点,这 N 个景点由 N-1 条道路连接而成,我们保证这 ...