Go Language Grammar summaryCategory: Technical 2013-09-16 14:21 3007 People read comments (0) favorite reports Go Language Golang concurrency syntax
Directory (?) [+]
Recently looked at Golang, the grammar of Go language summed up a bit, make a quick reference
Data type
var varName type
,,,,,, var var1,var2… type
var varName type = Value
var varName1,varName2 type = Value1,Value2
var varName1,varName2=Value1,Value2
varName1,varName2:=Value1,Value2
define the data type.
Declares that the variable that is not being used will be wrong at compile times.
Constant definition: const varName = Value
,const varName type = Value
string
String type values are immutable, but can be sliced, strings can be used +
to connect
iota
Used to declare enum
, which represents the self-added 1, initially 0
var arrayName [N]type
Used to declare an array, or use arrayName := [N]type{ v1,v2…}
to declare
Array declarations can be nested
slice
Used to represent slices, declaratively, var sliceName []type
orsliceName := []type{v1,v2…}
slice
Save a reference, not an entity
slice
There are some built-in functions to len
get the length, cap
get the maximum capacity, append
append the data, and copy
use to copy the data
map
Declared by var mapName map[keyType] valueType
ormapName := make(map[keyType]valueType)
map
Can be key : value
initialized by
make
Memory allocations for built-in types new
for various types of memory allocations, new
returns a pointer and make
returns a value other than 0
Process Control
if
Statements do not require parentheses and can be declared in an if statement, using if
the conditions of the split statement
if x:=function();x<10 { fmt.Printf("x < 10,%d\n",x); }else{ fmt.Print("x >= 10 ,%d\n",x); }
goto
Statement is similar to the C language, but jumps to a label that must be defined within the current function
for
Statements are similar to the C language, but break
continue
can be labeled and jump out of multiple loops.
switch
Statement break
, if you want to forcibly execute the following case, you can use thefallthrough
Function
How to declare:
func funcName(input1 type1, input2 type2) (output1 type1, output2 type2)
func
Used to declare a function, the function is named funcName
, followed by the input, the output data type.
function can have multiple return values
The function's value operation and pointer operations are similar to the C language, and the built-in types, string
slice
map
directly using a similar pointer pass, do not use the fetch address character, but if you need to change slice
the length, you need to take the address to wear the pointer.
defer
Statement is used to represent statements executed before a function is returned.
type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
Used to declare a function type, mainly used in higher-order functions.
import
Used to import packages, package
to export packages, to use operators for package operations .
struct type
How to declare:
type Person struct { name string age int }
Anonymous, anonymous mode A contains all the types of B
type Student struct { Person // 默认Person的所有字段 speciality string }
If there are fields in the anonymous type that conflict with itself, you can use anonymous type + .
access
Type of method declaration:
func (r ReceiverType) funcName(parameters) (results)
You can use: type typeName typeLiteral
from a defined type, you can use a method to extend the functionality of the type after you have defined it.
When you need to change the value inside a struct, you need to ReceiverType
define it as a *
pointer type, but you don't need it when you call it, and the go language automatically helps you do it.
Method can be inherited and can be overloaded
Interface interface
type InterfaceName interface
Used to defineinerface
The interface type defines a set of methods that implement this interface if an object implements all the methods of an interface.
Empty interface (interface{}) does not contain any method, because of this, all types are implemented with NULL interface
A function takes interface{} as an argument, then he can accept any type of value as a parameter, and if a function returns interface{}, it can return any type of value
value, ok = element.(T)
, here is value
the value of the variable, ok
is a bool
type, element
is a interface
variable, T is the type of the assertion, if ok
it is, it true
element
is indeed T
of type.
interface
can be nested
Concurrent
Using go
keyword + to 函数名
implement concurrency
Use channel
to implement inter-thread communication, channel
by make
constructing, using <-
to send and receive data.
chan
is channel
the keyword, followed by the data type to ch <- v
send the data, receive the v:=<-ch
data, ch
is the chan
type.
package main import "fmt" func sum(a []int, c chan int) { total := 0 for _, v := range a { total += v } c <- total // send total to c } func main() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from c fmt.Println(x, y, x + y) }
channel
The default is blocking, which allows for thread synchronization.
ch := make(chan type, value)
The value
buffer length of the CHANNL can be set by setting a different channel when constructing it.
close
Used to closechannel
Use select
+ case
to select multiple channel
Use select
+ case <- time.After(5 * time.Second)
to set timeouts
Goexit
Exits the currently executing goroutine, but the defer function also continues to invoke the
Gosched
With the execution permission of the current goroutine, the scheduler schedules other waiting tasks to run and resumes execution from that location at some point.
NumCPU
Returns the number of CPU cores
NumGoroutine
Returns the total number of tasks that are in the line of practice and queued
GOMAXPROCS
Used to set the number of CPU cores that can be run
Go Language Grammar summary (GO)