GO language Learning

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




Installation:

sudo apt-get installgolang-go

Export goroot= $HOME/go

Exportpath= $PATH: $GOROOT/bin



One,Hello World program

Package main//This packet is named import "FMT"//contains "FMT", in FMT there is input output func main () {FMT. Printf ("Hello world!\n");}


Note : the main () function, curly brace "{", is the same line as the function name , and the compiler will give an error if the C language is the same.


Compile:

Go Build A.go

the a.go here is the source file name


Two use hash table

Package main import ("FMT") type Data struct{date string; value int;} func main () {FMT. Printf ("Hello world!\n"); var m = make (Map[string]int); Create a blank hashm["str1"] = 10; m["str2"] = 1000; Fmt. Printf ("%d\n", m["str1"]); Traverse hashfor name,value: = range m {fmt. Printf ("%s\t%d\n", Name,value); } }



Three-assignment statement features

googledocument References:

Multipleassignment

Thelanguage specification has long guaranteed, in assignments theright-hand-side expressions is all evaluated before Anyleft-hand-side expressions is assigned. To guarantee Predictablebehavior, Go 1 refines the specification further.

Ifthe left-hand side of the assignment statement contains expressionsthat require evaluation, such as function calls or AR Ray Indexingoperations, these'll all is done using the usual left-to-right rulebefore any variables is assigned their V Alue. Once everything isevaluated, the actual assignments proceed in Left-to-right order.

Theseexamples illustrate the behavior.

SA: = []int{1, 2, 3}    I: = 0     i, sa[i] = 1, 2  //sets I = 1, sa[0] = 2     SB: = []int{1, 2, 3}    J: = 0     Sb[j], j = 2, 1  //sets Sb[0] = 2, j = 1     SC: = []int{1, 2, 3}     sc[0], sc[0] = 1, 2  //sets Sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end)     

Updating : This is a change where tools cannot help, but breakage is unlikely. No code in the repository is broken by this change, andcode that depended on the previous unspecified behavior W As Alreadyincorrect.


Definition and use of four functions


Package main import ("FMT")//  (x int) is the parameter table//(r int) is the return result of the Func fun (x int) (r int) {if x = = 1 {return 1;} else {return Fun (x-1) * x;} return; } func Main () {FMT. Printf ("%d\n", Fun (3)); }




Wuchang Quantity and variable

Package main import ("FMT" "OS") const PI = 3.14; Defines a constant variable, a const PP = 2/3; Func main () {var a int = 10;//defines an integer variable and is initialized to 10var goos = os. Getenv ("PATH"); Gets the system environment variable FMT. Printf ("%s\n", GOOS); Fmt. Printf ("%f\n%d\n", pi,pp); Fmt. Printf ("%d\n", a); }






Six Time savers:short Declarations anddistributing

Before defining a variable method:

var a int = 10;

To save time, we can define the following:

A: = 10;

The system defines a variable based on the type of the number



Seven basic data types

Number:

int, uint, float, uintptr



The UIntPtr data type is a special data typethat are an

Unsigned integer that would be large Enoughto store a pointer

Value.



int, uint, floatthe length is based on the platform, if it is64bitplatform,Intand theUIntlength is64bit, if it is+ bitPlatform,the length of it is32bit;

The architecture-independent numeric typesare:

Uint8

Uintl6

UInt32

UInt64

int8

Intl6

Int32

Int64

Float32

Float64

Byte(Thebyte is a familiar alias for Uint8. )



Note:

{

var a int8 = 10;

var b int16 = 100;

b = A;

}



This program would generate a compiler error:

Cannot use Rny16bitint (type Int16) as

Type Int32 in Assignment



String:

var str string;// definition

str = "Abcdeft";

Fmt. Printf (str);// output

Str[0] is 'a ',index starting from 0



Eight use Strings Package

Strings. Hasprefix (strstring, prefix string) bool;//determine if there is a prefix prefixstrings. Hassuffix (strstring, suffix string) bool;//determine if there is a suffix suffixstrings. Count (strstring,sub string) int;//calculate how many substring substrings. Index (str string, sub string) int;strings. Lastindex (str string, sub string) int; return-1strings if not found. Repeat (str string, Count int) string;//copies str several times, returning the copied string for example: str = "abc"; str1 = strings. Repeat (str,3);//At this point the value of STR1 is abcabcabcstrings. ToUpper (str string) string;strings. ToLower (str string) string;



Nine Strconvpackage Use

Package Mainimport ("FMT" "StrConv") func main () {var II int = 1100;var str2 String;var str1 = "1235"; var err error;ii,err = StrConv. Atoi (STR1); if err = = Nil {fmt. Printf ("%d\n", ii);} STR2 = StrConv. Itoa (ii); FMT. Printf (STR2);}



Ten conditional statements

If condition {} else {}//********************************if initialization_ Statement Condition {} else {}//*****switch**********************************************package mainimport ("FMT") Func Main () {var a int = 100;switch a {case  100:fmt. Printf ("a<100\n"); case  111:fmt. Printf ("a > 111\n");d efault:}}//----------------------------------------------------------------------------- --------------Package Mainimport ("FMT") func main () {var-a int = 100;switch {case  a< 100:fmt. Printf ("a<100\n"); case  a > 111:fmt. Printf ("a > 111\n");d efault:fmt. Printf ("else\n");}} //***************************************************



11 Loop Iteration



/******************************************************************package mainimport ("FMT") func main () {for i:= 0; I < 100; i++ {fmt. Printf ("%d", I);}} //----------------------------------------------------------------------------------------------------------



12 Custom Functions

1. Func fun (a int) int {

}

2. Func Fun (A, b int) (int, int) {

return a, B;

}

in the go language, it is allowed to return multiple values



13 using defer(delay)



Package Mainimport ("FMT") func fun1 () {fmt. Printf ("abc\n");d efer fun2 ();//wait until the end of fun1 execution, and then automatically execute fun2 (); fmt. Printf ("eft\n");} Func fun2 () {fmt. Printf ("fun2\n");} Func Main () {fun1 ();}



14 using blank identifier "_"

Package Mainimport ("FMT") func fun1 () (int, int) {return 1, 2;} Func main () {var a int;a,_ = Fun1 ();//Use  _ to record the return value not recorded in FMT. Printf ("%d\n", a);}


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.