Go Language Primer "three": Learn go syntax with a piece of code

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

Write in front

The syntax of Golang is simple enough, but it changes a lot, just need to master the typical usage , do not need to know all the syntax sugar, so the code will not contain all possible grammatical forms.

Concurrency is a major theme of Golang, followed by a dedicated section that does not appear in this section.

There are also some "conventions":

    • Visibility. There are private,protect,public in Java. Golang default is the first letter case to determine: the first uppercase variables, methods are public, all the scope is visible, the first letter lowercase is private, the file is visible.
    • Simplicity. The package imported by import and the defined variables must be used, or the program will not compile. Therefore, the code var p ClassA is not a declaration definition, but contains initialization , in fact the memory has been allocated, which is easy to ignore.

The following code:

A normal Go language code, for Go language learning, the author of the 2016-11-29//declaration package, the package name and directory path consistent, to $GOPATH/SRC as the root, such as Src/math/add.go's package for math. In addition, if it is a portal (that is, contains the main function), the package name is main, which can be compiled into an executable file by Go build. Package main//Block Import Note://import must be used, not import, but not his import ("Fmt" "StrConv" "reflect")//block definition variable var (//INT type Includes Rune, Int8, Int16, Int32, Int64 and Byte, Uint8, UInt16, UInt32, UInt64.    Where Rune is Int32 's nickname, Byte is Uint8 's nickname. myInt int//float includes float32,float64 myfloat float32 mybool bool myString string)//block Declaration Const Const (Conststrin    g = "Hello World, Worlds")//Globally defined variable var globaldefinedvar interface{}//defines a struct (also a class, because Golang does not have the concept of a Class), object-oriented type person struct {    The member function of the name string age Int}//person, explicitly specifying p, the this pointer in Java, the function in Python the first parameter Selffunc (P *person) introducemyself () { Fmt. Println ("My name is" + p.name) fmt. Println (P.age)}func (P *person) shoot () {fmt. Println ("I can shoot, so I can play football.")} Defines an interface type Footballplayer interface {shoot ()}func main () {//////////////1. Variable definition////////////var localstring string localstring = ' string is a pair of double quotation marks (representing a single line) or an inverse quotation mark (representing multiple lines) that defines the '//////////////2.rune, byte array, string relationship Myrune: = ' i ' FMT. Println (Myrune)//rune converted to a string myrunestring:= string (myrune) fmt. Println (myrunestring)//rune converted to byte array bytes:=[]byte (myrunestring) fmt. Println (bytes)//interface{} type can be assigned any type, Java-like object type Globaldefinedvar = localstring Newvar: = ": = is a shorthand form of declaration and initialization, Automatically inferred type "FMT" by the system.  Println (Newvar)//////////////3. Array definition and initialization////////////myArray: = [3]int{1, 2, 3}//array definition, default initialized to 5 0 var MyArray2 [5]int FMT. Println (myArray2) fmt. Println (MyArray)//////////////4.slice////////////Myslice: = []int{1, 2, 3, 4}//create slice from array, note 1: How to use, from The first element is taken to the end, and [1:4] can be taken from the first to the fourth (not included). From Python (author note) MySlice2: = myarray[1:] Myslice=append (myslice,5,6,7)//////////////5.if,else block nothing special, mybool undefined The default is false, which executes else////////////if Mybool {fmt. Println ("if")} else {fmt. PrinTLN ("Else")}//////////////6.for loop////////////for index, Value: = Range Myslice {fmt. Printf ("index:%d,value:%d \ n", index, Value)} for (true) {FMT. Println ("can also be used this way, equivalent to while (true)")//Avoid infinite loops, direct break off break}//////////////7.map Create, delete and use, the range keyword makes With////////////MyMap: = Make (Map[string]int) mymap["a"] = 1 mymap["b"] = 2 mymap["C"] = 3 Delete (MyMap, "a") for key, value: = Range MyMap {fmt. Printf ("Key:%s,value:%d", key, Value)}//////////////8. Object-oriented//////////////object initialization in two ways, the first is to return a pointer, the second return    is the object. Note that new always returns the pointer jack: = new (person) Jack.name = "Jack" jack.age = "Amy": = person{"Amy", + Jack.introducem    Yself ()//proof is pointer (*jack). Introducemyself () amy.introducemyself ()//Throw exception Invalid indirect of Amy (type person) (*amy). Introducemyself () fmt. Println (reflect. TypeOf (Jack)) fmt. Println (reflect. TypeOf (Amy))//////////////9. Interface using//////Interface assignment, you can see that Jack's person class does not need to implement the interface can be implemented, only need to have the interface required functions.  var footballPlayer1 = Jack Footballplayer1.shoot ()//function call, can return multiple values myString = "Golang is awesome" myRet1, MyRet2 : = Receive2return2 (myString, myInt) fmt.    Println (MyRet1, MyRet2)//////////////10. Exception Handling//////////////error handling, calling a method of throwing exceptions malfunction ()//Two knowledge points:    1.recover collects exception information thrown by panic in the call stack//2.defer execution time is the execution of the defer function exits, similar to the last in Java, but does not need to enclose a large piece of code in curly braces, so that the level of code is reduced. Defer func () {if err: = Recover (); Err! = nil {fmt. PRINTLN (Err)}} ()//each defined variable and constant is to be used, no garbage is allowed, here is a print fmt.    Println (Mybool, Myfloat,conststring,myslice2)}func receive2return2 (param1 string, param2 int) (Ret1 string, Ret2 int) { Fmt. Println ("param1:" + param1) fmt. Println ("param2:" + StrConv. Itoa (param2)) return "returned" + param1, param2 + 1}func malfunction () {Panic ("some thing went wrong!")}

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.