Golang Learning Series (2)-Language basics

Source: Internet
Author: User
Tags new set
This is a creation in Article, where the information may have evolved or changed.
本文是学习Golang语言的系列文章之一,主要描述go语言的基础语法,以及进行实践的相关代码

Golang keywords

The go language is a compiled language similar to the C language, with a total of 25 keywords.

break selectcaseelseiftype continueforreturn var

The first simple Go program

Learning any language, basically from the output of the simple Aello World began, this article still think this way is more cool, @_@.

本文以GOPATh=/home/xialingsc/go为例,作为代码空间。在$GOPATH"fmt"func main(){    fmt.Println("Hello World,This is xialingsc");}

Explanation: Go is organized through the package, and each of the go language programs that can be run independently must contain a packages main. In this main

The package must contain an entry function, main, which has no parameters and no return value. The go language natively supports UTF-8 encoding, any character

Can be output directly, and any character in UTF-8 can be used as an identifier.

Some rules of Go

Go uses the default behavior to be concise.

    • A variable that begins with a capital letter can be read by another package, is a common variable, and a lowercase letter starts with a private variable and cannot be exported.

    • Functions that begin with capital letters also follow these rules

Defining variables

Format: var variableName type

Define multiple variables

var v1,v2,v3 string

Defining variables and initializing values

var v1 int = 10

Simultaneous initialization of multiple variables

var v1,v2,v3 int = 6,7,8

Simple declaration assignment in the body of a function

A,b,c: = 8,9,10

_ (underscore) is a special variable name, any value given to it will be discarded, why do we still use it? This is the performance of go flexibility, in some

scenario, the resulting return value is not actually useful in the next program, but if it is declared, go will indicate the error at compile time.

Constant

Constants are values that are determined at compile time and cannot be changed while the program is running. Constants can be defined as types such as numeric values, Boolean values, or strings.

Format: const CONSTNAME type = value

For example: const PI float32 = 3.141516926 or const PI = 3.141516926

Eight built-in base types

Boolean

In the Go language, the Boolean value is bool, the value is true or FALSE, and the default is False.

Format: Var variableName bool

Numeric type

(1) Integer type

Integer types are both unsigned and signed, and go supports both int and uint two, both of which are of the same length, but depending on the length of each

The implementation of the compiler.

Integer types are divided into: Rune, Int8, Int16, Int32, Int64 and Byte, Uint8, UInt16, UInt32, UInt64

Byte is a nickname for Uint8.

Note: These types of variables are not allowed to assign values or actions to each other. Although the length of int is 32bit, the default value is 0, but int and int32 are not interoperable.

(2) Floating-point number type

There are two kinds of floating-point types, float32 and float64, which are float64 by default.

In addition, go also supports the plural, the format is Re+imi, there are two kinds, respectively, is complex64,complex128, the default is complex128

For example: var c complex64 = 10+12ifmt. Printf ("Value is:%v", c)

String

The strings in-go are encoded in the UTF-8 character set, and the strings are defined by a pair of double quotation marks ("") or an inverse quotation mark ("'), type string

Format: var abcstr string = "abc"

The string in-go is immutable, for example: abcstr[0] = ' C ' will compile an error. If you really want to make a change, you can achieve:

NEWSTR: = []byte (ABCSTR)//convert string abcstr to []byte type]

Newstr[0] = ' C '

ABCSTR1: = String (NEWSTR)

Fmt. Println ("%s \ n", ABCSTR1)

-Can connect two strings with "+" operator

-Modifying strings can also be modified using slices (described later)

ABCSTR: = "Oldstr"

ABCSTR = "new" + Abcstr[3:]

    • You can also declare a multi-line string
abcstr :=`muli            string`

Type of error

There is an error type built into go, specifically to handle the wrong message. The go package also has a packet errors to handle the error.

Err:=Errors. New("Ceshi Errors")ifErr!=Nil{Fmt. Print(Err)}{R Endraw%}{% Endhighlight%}# # # Iota EnumerationGo has a keyword iota, mainly used to declare an enum, the default start value is 0, each call plus 1, if the new declaration of another set of enum(That is, a new set of const), Iota starting from 0{% Highlight%}{% RAW%}Const(    a =Iota//x=0b =Iota//y=1 c//c=2, when omitted, defaults to the same literal as the previous value D//d=3)Conste =Iota//e=0

Array arrays

Format: Var arr [N]type, subscript starting from 0, the array as a parameter passed into the function, is actually a value assignment, not a pointer, the pointer can be used slice.

[3]inta[0]= 1fmt.Println("The first number is %d\n",a[0]) //1fmt.Println("The last number is %d\n",a[2]) //0//其他声明与赋值a :=[3]int{1,2,3} //声明长度为3并赋值b :=[5]int{1,2,3} //声明长度为5,并赋予前三个分别为1,2,3,其他为0c :=[...]int{1,2,3} //省略长度,又Go自动根据元素个数来计算长度

Support for nested arrays in go, i.e. multidimensional arrays

MultiArray:= [2][3]Int{[3]Int{The},[3]Int{4,5,6}}Because the internal and external types are identical and are all int, it can be omitted as: MultiArray:= [2][3]Int{{The},{4,5,6}}For example: Dobulearray:= [2][4]Int{{1, 2, 3, 4},{5, 6, 7, 8}}Fmt. Println("The first element of Dobulearray is%d:", Dobulearray[0][0])Fmt. Println("The last element of Dobulearray is%d:", Dobulearray[1][3])

Slice

This is one of the features of the Go language, which is a reference type with dynamic array attributes, and does not know how large the array scenario would be if the initial definition was met.

Format: Var Slicearr []type, less than array type length

For example: buf: = []byte{' A ', ' B ', ' C '}

Slice can be declared from an array or an existing slice, by array[i:j], I is the start position, J is the end position

But does not contain array[j], length is j-i

Declares an array var with a length of 10 elements of type ByteInitarray = [10]Byte{' A ',' B ',' C ',' d ',' E ',' F ',' G ',' h ',' I ',' J '}Declares a slicevar of two byte aslice,bslice[]byte//points to different positions in the arrayAslice =Initarray[2:5]The Aslice contains Initarray[2], Initarray[3], Initarray[4]Bslice =Initarray[3:5]The Bslice contains Initarray[3], Initarray[4]

Easy operation of the slice

Default start location is 0,initarray[: 2]Equivalence and Initarray[0:2]Slice the second sequence defaults to the length of the array, Initarray[2:]Equivalent to Initarray[2:len(Initarray)]Initarray[:]Equivalent to Initarray[0,len(Initarray)]The length len of the slice is different from the capacity cap, which refers to starting from the position specified by the slice, until the last value of the original array because slice is a reference type, so when the reference changes the original value, all other references change the value conceptually, slice like a struct , this structure contains three elements, a pointer, Len length, and a maximum length of capslice built-in functions: Len,cap,append(Append, and then return to the same type of slice), copy(Copy elements from the source slice src to the target DST, and return the number of copied elements usage: slice:= []Byte{' A ',' B ',' C ',' d ',' E ',' F ',' G '}Copyslice:= []Byte{' x ',' y ',' Z '}Copy(Slice, Copyslice)Fmt. Printf("The Element of Copyslice is%s\n", Copyslice)Fmt. Printf("The Element of Slice is%s\n", Slice)Sliceeven:=Make([]int, 0)Sliceeven =Append(Sliceeven, 1, 2, 3, 4, 5)

Map

Format: Map[keytype]valuetype

The map reads and sets the same as slice, through the key operation, just slice index is the int type, and map more other types

The type of = = and! = operations can be defined for int,string and all

Declares that a key is a string, and a map with a value of int must be initialized with make before use.

var dictionary map[string]int

Dictionary = Make (map[string]int)

Another way of declaring a map, using make initialization

Numbers: = Make (Map[string]int)

numbers["one"] = 1//Assignment

Fmt. PRINTLN ("Test output:", numbers["one"])

A few things to keep in mind when using map:

Map is unordered, each printout is not the same as the map length is not fixed, belongs to the reference type built-in Len function, the number of keys to return map to modify the value of map, you can directly numbers["One"] =12map initialization can be implemented by means of Key:val, the map contains a way to determine if there is a key, delete the elements of the map via delete//Initialize a maprating:=Map[String]Float32{"C": 5,"FO": 3.4,"Python": 2.3}Ratingvalue, OK:=Rating["C #"]ifOk{Fmt. Println("C is in the map and it ' s value is:%d\n", Ratingvalue)} Else {Fmt. Println("C isn ' t in the map")}Remove Delete(Rating"C")Fmt. Println("Itretor map start:") for_, Value:=Range Rating{Fmt. Println("The element of map is%s", value)}

Make and new operations

Make memory allocations for built-in types (Map,slice,channel)

New is used for various types of memory allocations, new returns a pointer, and new (T) allocates a 0 value padding for the T-type memory space, returning a value of type *t

Make (T,args) differs from New (T):

Make can only create Slice,map and channel, and return a T type with an initial value (not 0), instead of *t.make returning the initialized (not 0) value.

  common type variables are not populated before the default value int 0int8 0int32 0int64 0uint. 0x0rune 0 //rune actual type int32byte 0x0//byte actually uint8float32 0 //Length 4 Bytefloat64 
    
     0 //length 8bytebool 
     false  string 
      ""  
     
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.