Go language One--basic

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

Refer to "Go_web_ Programming. pdf"

See Also:

Go language Introduction (top)-syntax

Go language Brief (bottom)-Features

Start by writing a simple script hello.go

/** Definition Package Name *  main    means you can run standalone *  [other] compile build. A file */package main/** introduce system level package Fmt*/import "FMT"//Main.main Is the entry point for each executable program, func main () {        fmt. Printf ("Hello, World or Hello, worlds orこんにちは world \ \")}

Run as follows:

> Go run hello.go #直接运行脚本Hello world>> go build hello.go #编译生成可执行文件或库文件//generate hello>> Go clean #删除

Variable definition

Package Mainimport "FMT"//var VName type = value, general use of the VAR keyword to define the global variable var g_val1 int32 = 100//:= assignment can only be used in the function body, cannot be used to create global variables//g_va L2: = 100//constant Definition Const CINT = 1const Cint2 int = 1const CStr string = "Hello" Const CSTR2 = ' Hello '//string in double or inverted quotes, cannot use single quotation mark The declaration does not use global variable compilation to run without error var bval boolfunc main () {        fmt. Printf ("Global g_val1 =%v\n", g_val1)        //var vname1,vname2 type        var l_val1, l_val2 float32 = 1.2, 2.3        FMT.  Printf ("Local l_val1 =%v, L_val2 =%v\n", l_val1,l_val2)        //vname1,vname2: = Value1,value2        l_val3, L_val4: = 2.3, 4        FMT. Printf ("Local l_val3 =%v, L_val4 =%v\n", L_VAL3,L_VAL4)        //declares that a local variable is not used in the compile phase will error        //var L_VAL5 int}

Data type

Package main//Group Declaration import (        "FMT"        "errors") const (        i = 0        s = "test") Func main () {        //different data types cannot be converted directly, Despite the same length as        var (                a int = 3                b int32                C rune = 4        )        B = a//error        b = C//ok        //cannot use a (Typ e int) as type int32 in Assignment        //string concatenation with "+" sign        name: = "You" + "good"        name = "World"        fmt. Printf ("name =%v\n", name)        //Output "World"        err: = errors. New ("Custom error message \ n")        if err! = Nil {                FMT. Print (ERR)                //Output "Custom error Message"}        }

Go is so concise because it has some default behavior:
• Variables that begin with capital letters are exportable, that is, common variables that other packages can read, and lowercase letters that start with non-exportable, private variables.
• The same as the function that begins with the uppercase letter, which is equivalent to the public function in class with the common keyword; the lowercase letter begins with the private function with the private keyword.

Array manipulation

Package main//Group Declaration import ("FMT"//referenced packages are not used when compiling error//"errors") func main () {//array declaration var arr [] int arr[0] = 3 FMT. Printf ("arr[0] =%v and arr[4] =%v\n", arr[0],arr[4])//Output 3 and 0 arr2: = [10]string{"name", "Age"} arr2[0] = "Nick Name "FMT. Printf ("arr2[0] =%v and arr2[4] =%v\n", arr2[0],arr2[4])//output nickname and empty//multidimensional arrays Doublearray: = [2][4]int{[4]in t{1,2,3,4},[4]int{5,6,7,8}} fmt. Printf ("doublearray[0][0] =%v\n", doublearray[0][0]) Easyarray: = [2][4]int{{1,2,3,4},{5,6,7,8}} FMT. Printf ("easyarray[0][1] =%v\n", easyarray[0][1]) ARR3: = [5]int{1,3,5,7,9}//dynamic array slice, definition missing length var sarr1,sarr2 [] int sarr1 = Arr3[2:3]//sarr1 = {5} SARR2 = arr3[1:]//SARR2 = {3,5,7,9} fmt. Printf ("sarr1[0] =%v\n", sarr1[0]) fmt. Printf ("sarr2[0] =%v\n", sarr2[0]) fmt. Printf ("len (sarr1) =%v\n", Len (SARR1))//Gets the array length FMT. Printf ("cap (SARR1) =%v\n", Cap (SARR1))//Gets the maximum number of arrays sarr1 = append (sarr1,6)//Append Data SARR1 = {5,6} fmt. Printf ("SARR1[1] =%v\n ", sarr1[1]) sarr2 = Sarr2[:len (SARR2)-1]//delete End element} 

Arr: = []STRING{STR1}

Slice has some simple operations
The default starting position for Slice is 0,ar[:n] equivalent to ar[0:n]
The second sequence of slice is the length of the array by default, Ar[n:] equivalent to Ar[n:len (AR)]
• If you get slice directly from an array, you can ar[:] because the default first sequence is 0, the second is the length of the array, which is equivalent to Ar[0:len (AR)]

package mainimport ("FMT") func main () {var (m_val1 map[string] s Tring)//Declaration dictionary needs to call make initialization M_val1 = Make (map[string] string) m_val1["name"] = "Ciaos" M _val1["hobby"] = "Game" FMT. Printf ("name is%v and hobby are%v\n", m_val1["name"],m_val1["Hobby"]) M_val2: = Make (map[string] int) m_val2 ["First"] = ten fmt. Println ("Dictionary content:", "first =", m_val2["first"])//Output "dictionary content: first = 10"//Initialize a dictionary m_val3: = Map[string] int{"A": 1, "B": 2, "C": 3} fmt.                Println ("Length of M_val3 is", Len (M_VAL3))//Get the specified key corresponding to alue num,ok: = m_val3["D"] if OK { Fmt. Println ("m_val3[\" d\ "] is", num)} else {fmt. Println ("m_val3[\" d\ "] is invalid")} delete (M_val3, "B")} 

A few things to keep in mind when using the map:
map is unordered, each printed map will be different, it cannot be obtained through index, and the length of the
map must be obtained by key is not fixed, that is, like slice, is a reference type The built-in Len function also applies to the map, which returns the number of keys owned by the map
map can be easily modified by numbers["One"]=11 can easily change the key to one's dictionary value to one
map initialization can be The values are initialized by Key:val, and the map has a built-in way to determine if a key exists
make is used for memory allocations of the built-in types (map, slice, and channel). New is used for various types of memory allocations

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.