Golang Basic Learning

Source: Internet
Author: User
Tags try catch
This is a creation in Article, where the information may have evolved or changed.

1. Basic Concepts and syntax

    • In Golang, if the first letter of a name is capitalized, the name of the word will be exported.

    • The Golang program consists of a package, which runs from the main package, where multiple source files can belong to the same package, but only one package is placed in a directory. Typically, the directory name is the same as the package name. package maindefine a package main. The import code package is in the following form:

  

Import "Fmtimport" Math/rand "  or write as import (" FMT "" Math/rand ")
    • Function: When defining a variable, the variable name precedes the type, which is inconsistent with many languages. And x int,y int can be expressed as x,y int . Define a function form as follows:
Func Add (x int,y int) Int{return X+y}

Functions can return multiple values:

Package Mainimport "FMT" Func swap (x, y string) (string,string) {return Y,x}func main () {a,b:= swap ("Hello", "World") fmt. Println (A, B)}
注:返回值可以指定变量名,并且像变量一样使用。
Func (P myType) FuncName (A, B int, c string) (R,s int) {return}
func-> Keyword funcname-> method name a,b int,c string-> incoming parameters r,< Span class= "Hljs-title" >s int-> return value {}-> function body function definition You can use var: var m int = 10 or, var i,j,k = 1,2, 3 variable assignment in function use: = operator              The        
function is also a type, and the function type is an important type in the go language.
var recorder func (name string,age int,seniority int) (done bool)//After all implementations conforming to this function type can be assigned to the variable recorder, as follows recorder = func (name String,age int,seniority int) (done bool) {//corresponding statement return}

In the above, we assign a function literal to the variable recorder, and we can invoke it directly on a variable of a function type by applying the invocation expression as follows:

Done: = Recorder ("Harry", 32,10)

Type Encipher func (Planintext string) []byte//type is specifically used to declare a custom type, as declared here
Encipher is actually an alias type of function type func (Planintext string) []byte.

    • 数据类型:数据类型的转换表达式为T(v),含义将v转换为类型T。数据类型包含如下形式:
1.bool2.string3.intint8 int16 int32 int644. UINT uint8 unint16 uint32 uint64< Span class= "Hljs-number" >5. uintptr 6. Byte (equivalent to uint8) 7. Rune (equivalent to int32, which represents a Unicode code point) 8.float32,float64 9. Complex64,complex128 Note: Use constant to define constants, constant pi= 3.14  
  • Control statement:
      1. < Span class= "Hljs-keyword" > for statement Golang (and use only) for sequential (without a while statement)
Package MainFunc Main () {sum: = 0for I: = 0;i < 10;i++{  sum + = i}//The following notation is equivalent to the while statement for sum < 1000{su in languages such as C + +  m + =sum}} Note: The For Loop statement does not require () and {} must be used, if, switch syntax is handled as such. If you use an infinite loop, you can use: for{}

2. If statement, the IF statement can take a statement before the condition is executed (this is often referred to as the If band on a phrase), the life cycle of the variable in the word sentence ends after the IF statement, as follows.

Package Mainimport (  "FMT"  "Math/rand") func main () {  if n: = Rand. INTN (6); n <= 2{    fmt. Println ("[0,2]", N)}else{fmt. Println ("[3,5]", N)}//here cannot use variable n}

3. Switch statement, Golang does not need to use the break statement to jump out of switch, and switch can have no conditions.

Package Mianimport (  "FMT"  "Runtime") func main () {  fmt. Print ("Go runs on")  //switch similar to if can bring up a phrase  switch OS: = Runtime. goos;os{case  "Darwin": FMT. Println ("OS X.")  Case "Linux": FMT. Println ("Liunx.")  Default://othersfmt. Printf ("%s.", OS)  }}//unconditionally uses the SWITC statement func main () {  T: = time. Now ()  switch{case  T.hour () < 12:fmt. Println ("Good morning!")  Case T.hour () < 17:fmt. Println ("Good afternoon.")  Default:fmt. Println ("Good eventing.")  }}

4. The Defer,defer statement can add a function call to a list (the function call is called a deferred function call) and invoke the function in the list at the end of the current function call. As follows:

Func CopyFile (DstName, SrcName string) (written Int64,err error) {  Src,err: = os. Open (SrcName)  if err! = Nil{return  }  defer src. Close ()  dst,err: = os. Create (DstName)  If Err!=nil{    return  }  defer dst.close () return IO. Copy (DST,SRC)}//Note: The deferred function call executes in the order of the advanced post-out: Func main () {  //output 43210  defer FMT. Print (i)}
    • Other data types

1. Structure, (structs), a structure is a collection of domains:

Type Vertex struct{  X int  Y int}func main () {V: = vertex{1,2}  v.x = 4  fmt. Println (v)  }

2. Array, [N]t is a type in Golang (like *t), representing an array of length n whose element type is T, the length of the array cannot be changed

Func Main () {  var a[2]string  a[0] = "Hello"  a[1] = "World"  fmt.println (a[0],a[1])  fmt.println (a)}

3. Pointers, pointers in Golang do not support arithmetic operations:

P: = vertex{x,y}//{x,y} is a struct LITERALQ: = &p//q type is *vertexq.x = 2  //Direct Access zone xstruct is wrapped by {}, The actual process we can use name: This syntax sets the value for a specific domain value: type Vertex struct{  x, y int}r: = vertex{x:3}  //The value of Y at this time is 0

The 4.slice,slice is variable length, which is a pointer rather than a value. []t is the slice type, where the element type is T:

P: = []int{2,3,4,7,11,13}fmt. Println ("p==", p) for I: = 0;i < Len (p); i++{  FMT. Printf ("p[%d] = =%d\n", I,p[i])  }} Note: Expression S[lo:hi] is used to create an element of slice, the newly created slice element is the [Lo,hi] position in S. Create slice using the Make function (not new) such as a: = Make ([]int,5)//len (a) is 5 here the Make function creates an array (the element is initialized to 0) and returns a slice point to the word array. Make can take three parameters to specify capacity: b: = make ([]int,0,5)//len (b) =0,cap (b) = 51 No value slice is nil, both length and capacity are 0var z[]intfmt. Println (Z,len (z), Cap (z)) if z = = nil{  fmt. Println ("nil!")}

5.map, used to map key to value (value), map can be created by make, not new

  Type Vertex struct{  lat,long float64}var m Map[string]vertexfunc main () {  m = make (Map[string]vertex)  m[" Bell Labs "] = vertex{40.23332,-31.32143,  }  fmt. Println (m["Bell Labs"])}//Note: Use [] to access values in map, use Delete to delete values in map m[key] = elem//Access Delete (M,key)//delete var m = Map[string]vertex {//Here Vertex can omit not to write  "Bell Labs": vertex{   34.34345,53,32123  },   "Google Labs": vertex{   34.34345,53,32123  },}//If you need to check if the key in the map exists//elem, OK = M[key]//elem Indicates the value of key (key does not exist, Elem is 0), OK indicates whether key exists

6.range, used to iterate over a slice or a map in for

var s = []int{1,2,3}func main () {for  i,v: = Range s{fmt. Println (i,v)  }  //requires only values, use _ Ignore index for  _,v: = Range s{fmt. Println (v)  }  //Only need to index for  i: = Range s{fmt. Println (i)  }}

7. Closures, the Golang function is also a value (just like an int value), and the function can be a closure. A closure is a function that references an external variable.

Package Mianimport "FMT" Func Adder () func (int) int{  sum: = 0  //Returns a closure that references the external variable sum  return func (x int) int{    sum + = Xreturn sum  }} Func Main () {  A: = Adder ()  FMT. Println (A (9527))}

 2. Methods and Interfaces

    • Method is a function that is attached to a custom data type, specifically a method that is associated with a recipient. Therefore, the signature of the method includes not only the function signature, but also a declaration about the receiver, that is, the declaration of the method contains the keyword func, the receiver declaration, the method name, the parameter declaration list, the result declaration list, and the method body. There is no class in Golang, you can define a method for the struct, with the following examples:
Package Mainimport (  "FMT"  "math") type Vertex struct{  x, y float64}//struct Vertex method//Here's Method Receiver V is of type * Vertexfunc (v *vertex) Abs () Float64{return Math. Sqrt (V.X*V.X+V.Y*V.Y)}func main () {  V: = &vertex{3,4}  fmt. Println (V.abs ())}

  注:此处方法的接收者使用指针类型而非值类型的原因如下:

  1.避免方法每次调用时,对接收者的不必要拷贝  2.在方法内可以修改接收者的值我们可以为任意类型定义方法,但以下情况除外:  1.如果类型定义在其他包中,不能为其定义方法  2.如果类型是基础类型,不能为其定义方法。
    • interface, an interface is also a type (like a struct). An interface type contains a set of methods, an interface type that holds the values that implement these methods, as follows:
Define interface Absertype Abser interface{  Abs () float}//define struct Vertextype Vertex struct{  x, y float64}//implementation Method Absfunc (V * Vertex) Abs () float64{  return math. Sqrt (V.X*V.X+V.Y+V.Y)}func main () {  V: = vertex{3,4}  //succeeded, able to hold value of *vertex type  var a abser = &v  //error, Cannot hold a value of type vertex  //Because method ABS is defined on *vertex, and  var b abser = v} is not defined on vertex
    • Anonymous domains, which can exist in structs with only types and no names, are called anonymous domains. Such as:
struct{  T1  *t2}

A domain or method in an anonymous domain in a struct can be accessed directly by this struct instance:

Package Mainimport "FMT" type Car struct{  wheelcount int}func (car *car) numberofwheels () int{  return Car.wheelcount}type Ferrari struct{  car}func Main () {  f: = ferrari{car{4}}  fmt. Println ("A Ferrari have this many wheels:", F.numberofwheels ())}

3. Concurrency support

    • Golang manages a lightweight thread at runtime (runtime), known as Goroutime. There is no problem creating a level hundreds of thousands of goroutine. Using the Go keyword opens a thread example as follows:
Package Mainimport (  "FMT"  "Time") Func say (s string) {for  I: = 0;i < 5;i++{time. Sleep (Time.millesecond) fmt. Println (s)  }}func main () {  //Open a goroutine execute say function  go say ("world")  Say ("Hello")}

4 other

    • Panic

The panic is used to indicate a very serious unrecoverable error. In the go language this is a built-in function that receives a value of type interface{} (that is, any value) as a parameter. The panic function is like the anomaly of our usual contact. However, go is not try...catch, so panic generally causes the program to hang (unless recover). So, the exception in the go language, that's really abnormal. You can try, call panic to see, the program immediately hangs, and then the go Run will print out the call stack. However, the key point is that even when the function is panic, the function does not go down, the runtime is not immediately upward transfer panic, but to defer that, and so defer things are running out, panic and then passed upward. So this time defer a bit like the finally in try-catch-finally. Panic is so simple. Throws a true sense of exception.

    • Recover

As mentioned above, panic's function does not return immediately, but defer first and then returns. At this time (defer), if there is a way to capture panic, and prevent panic transmission, then the exception of the processing mechanism is perfect. The go language provides the recover built-in function, mentioned earlier, once panic, logic will go to defer that, then we wait in the defer, the call recover function will capture the current panic (if any), the captured panic will not be passed up, Thus, the world resumed peace. You can do what you want to do. However, it is important to note that after recover, the logic does not revert to the panic point, and the function will return after the defer.

Go implements something like a try Catch package MainFunc Try (fun func (), Handler func (interface{})) {defer func () {if err: = Recover (); Err! = NI L{handler (Err)}} () fun ()}func main () {Try (func () {Panic ("foo")},func (E interface{}) {print (E)})}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.