Go Language Grammar summary (GO)

Source: Internet
Author: User
Tags constant definition

 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

  • stringString type values are immutable, but can be sliced, strings can be used + to connect

  • iotaUsed to declare enum , which represents the self-added 1, initially 0

  • var arrayName [N]typeUsed to declare an array, or use arrayName := [N]type{ v1,v2…} to declare

  • Array declarations can be nested

  • sliceUsed to represent slices, declaratively, var sliceName []type orsliceName := []type{v1,v2…}

  • sliceSave a reference, not an entity

  • sliceThere 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

  • mapDeclared by var mapName map[keyType] valueType ormapName := make(map[keyType]valueType)

  • mapCan be key : value initialized by

  • makeMemory 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
    • ifStatements 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);  }
    • gotoStatement is similar to the C language, but jumps to a label that must be defined within the current function

    • forStatements are similar to the C language, but break continue can be labeled and jump out of multiple loops.

    • switchStatement 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)
    • funcUsed 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.

    • deferStatement 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.

    • importUsed 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 interfaceUsed 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.

    • interfacecan 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.

  • chanis 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)  }
  • channelThe 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.

  • closeUsed to closechannel

  • Use select + case to select multiple channel

  • Use select + case <- time.After(5 * time.Second) to set timeouts

  • GoexitExits the currently executing goroutine, but the defer function also continues to invoke the

  • GoschedWith the execution permission of the current goroutine, the scheduler schedules other waiting tasks to run and resumes execution from that location at some point.

  • NumCPUReturns the number of CPU cores

  • NumGoroutineReturns the total number of tasks that are in the line of practice and queued

  • GOMAXPROCSUsed to set the number of CPU cores that can be run

Go Language Grammar summary (GO)

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.