Go语言内容基础篇|青训营笔记

124 阅读2分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记
本文章总结了Coursera上“Programming with Google Go Specialization by UCI"的第一个课程的第一周的部分内容,感兴趣的同学可以去Coursera上观看相关课程。 此次笔记为全英文。

Councurrency

Gorountine: represents concurrent task (you can imagine it as a thread)
Channel: is used to communicate between different task
Select: enables task synchronization

Workspace

Workspace has three subdirectories:

  1. src: contains source code files
  2. pkg: contains packages (library)
  3. bin: contains executables

By the way, the workspace directory difined by GoPath Variable, and the GoPath enviroment variable can be changed if you want to import some packages from other directories other than default workspace directory.

Packages

  • Group of related source files
  • Each package can be imported by other packages
  • First line of the source file names the package

Package Main

  • There must be a package called main for a program
  • Bulding the main package generated an executable program
  • Main package needs a main() function
  • main() is where code execution starts

The Go tool

  • A tool to manage Go source code

Go tool command

  • go build: compiles the programs. (Arguments can be a list of packages or a list of .go files. The go build tool creates an executable for the main package, same name as the first .go file.)
  • go doc: prints documentation for a package
  • go fmt: formats source code files
  • go get: downloads package and install them
  • go list: list all installed packages
  • go run: compiles .go files and runs the executable
  • go test: runs tests using files ending in "_test.go"

Naming for Variables

  • Case sensitive
  • Don't use keywords e.g. if,case,package,...

Type Declaration

  • Defining an alias (alternate name) for a type. Doing so may improve clarity, for example
type Celsius float64
  • With such alias, we can declare variables using the type alias.
var temp Celsius

Variables

  • Data stored in the memory
  • Must have a name and a type
  • All Variables must have declarations The most basic declaration
var x int

Here, var is the keyword, x is the variable name and int is the declared type. We can also declare as many variables as we want on the same line, for example

var x,y int

Initialize Variables

Initialize in the declaration

var x int = 100 //declare an integer with value 100
var x = 100 // Complier would recognize this variable as integer,
// an error would occur if you want to give x an value of 100.1.
  • Uninitialized variables have a zero value
var x int // x = 0
var x string // x = ""

Short Variable Declarations

We can perform a declaration and initialization together.

x := 100
  • Variable is declared as type of expression on the right hand side.
  • Note: We can only do this inside a function (we are not allowed to have such declaration outside a function)