Golang Grammar Learning (i): variables, constants, and data types

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

Learning a new language must start with his main grammar, which forms the basis of the entire program, and we can see some of the features of the language from the syntax. But then again. Grammar this thing, different language is similar, so this also to the grammatical memory caused certain difficulty. In fact the best way should be to have a book next to it. Can be consulted or corrected at any time. Of course, Golang's grammar is the same, the following is my study of seven Qiniu storage team Xu Xiwei, such as the "Go Language Programming":
Http://baike.baidu.com/link?

Url=vfrjnvjwitn0larbl7tmwypq5v8jlwzl_nycaqy6w0e7jxp6a4bgm61ge0ggmu6jnfqo_rnudgeqph7yk9w4s_
Grammar part of the time to sort out some, this book is very helpful for beginners to get started. In order to be able to recall in time. So it was recorded.

To avoid the long blog to bring about the reading fatigue. Try to streamline content and segmentation here.
This article mainly contains:
1. The Declaration, definition, assignment of variables and the concept of anonymous variables in go.
2. Definition and use of constants in Go
3. Supported built-in data types and how to use them in go
This is mainly the three parts, the overall introduction of such a language is the most important elements, like the composition of English 26 letters.

1. Variables in Go

1.1 Variable Declaration

The way variables are declared in Go is as follows:

var variable name variable type

var is a go-built keyword that is used to make "pure" variable declarations, paying attention to the sheer meaning of this. It is different from the system according to the value of the right value when the self-inferred variable type of a way, can feel is to define an absolute type of variable.
Example:

 var    v1    int    //定义一个整形v1 var    v2    [10]int   //定义一个整形数组v2 var    v3    struct  {          //定义了一个结构体    ...    f int     ...}

Wait a minute. So accustomed to C,c++,java and other language definition variables of the classmate also need to special memory of this definition. I do not know why go is so defined, I think it may be the inventor of the use of a language before the habit of it. But I do not know which kind, the reader who knows can also tell me.

(It was later found that this might explain why Golang's syntax is:
Http://blog.golang.org/gos-declaration-syntax) There is no need to write a semicolon of a statement, of course, plus will not error.
At the same time, to avoid writing Var repeatedly, you can define multiple variables together:

var {    v1  int    v2  string}

The assignment of 1.2 variables. Initialization

The assignment of variables in Go is very easy. Is after you have defined a variable. Assigns an initial value to a variable. There's no special place. Example:

varint10   //定义之后对i赋初值

But in go there is a very big reform is to agree to multi-assignment, in the past, in C, false assumptions on the I,J two variables to assign values, need two equal signs, such as I=3, j=4, but in go can be directly written:

ij34

Very easy. Suppose you want to exchange the value of a i,j, and you just need to write:

i , j = j, i  //这就是go创新的地方

The initialization of variables is similar to the assignment of variables. Just give the assignment directly at the time of the variable declaration, and support three types of initialization in Golang:

var variable variable type = initial value
var variable = initial value
Variable: = initial value
such as the following:

varint10  //最规矩的写法var10//编译器自己主动推算v2类型10    //同一时候进行变量的声明和初始化工作

Pay special attention to the ": =" symbol that has never been seen in C,c++,java, and he is able to shorten the number of lines in the code. The compiler should be explaining this sentence as two sentences, var v3 int, V3 = 10
So the left side of ": =" is a variable that has not been declared, otherwise it will be the following error, pay special attention to

No new variables on left side of: =

The concept of anonymous variables in 1.3 Golang

Readers with interpreted language such as Matlab should be impressed with the multiple return values of a function. In c,c++, assume that you want to return multiple values, either return a type, struct, or pass in a parameter to return a pointer to the type of the variable.

These are a way of directly supporting the function's multiple return values in Golang. But. Suppose that some of the many return values we don't need then what to do, similar to MATLAB. Anonymous variables are introduced here. "_" is, in fact, a default. For example in the book:

funcstring) {    return"may""chan""haha"//这里面就是一种缺省。值用来获得nickName

2. Constants in Go

Go also uses const to define constants, such as

"hellotest” //string类型const  1234  //32位整形常量等const (  //枚举类型,降低const的书写    0.0    eof = -1)

In addition, there are pre-defined variables, including the bool type "true", "false" and so on, as well as their own active growth of the iota.


Among them, Iota is placed 0 when the const is present. Then did not appear once iota oneself to add 1, until was again placed 0.

Like what

const (                     //iota被重设为0        iota            //a = 0        iota            //b=1        iota            //c=2

Note that because it is an enumeration, it can be simplified to

const (                     //iota被重设为0        iota            //a = 0        b                   //b=1        c                   //c=2

1.3 Go supported types

Let's take a look at the underlying types of go support. Then we wrap around some types to introduce some of the novelty features of go.
Same as the other types. Go support:

boolean bool
Shaping int8, Byte, int16, int, uint, uintptr
Floating-point type: float32 (float in c), float64 (double in c)
Plural type: complex64, complex128 (go in the special)
String: String (built-in type)
Character type: Rune (Unicode character type), Byte (UTF-8 character type)
Fault Type: Error
and composite types:
Pointer: pointer array: array slice: Alice
Dictionary: Map channel: Chan struct: struct Interface: interface
such as
Here's a look at these types of usage considerations:

1) type bool.

In the bool type. Unlike in C, a variable of type bool can only be assigned a value, true or false.

or a comparison operation. You cannot assign a value of 0, 1, or a 0,1 to a forced type conversion, such as

varbooltrue//正确varbool = (1==2// 正确varbool1// falsevarboolbool(1//错误

2) Plastic Surgery

In the shaping, go supports both signed and unsigned 8,16,32,64bit.

The UNIT8 is byte, similar to the char type in the C language. There are two different types of int and int32 in the Go language, so these two types of variables cannot be assigned to each other and perform operations. A forced type conversion is required if the operation is performed. At the same time, the shape of Go is similar to the C language, and it also supports numerical operations and comparison operations. and bit operations.

In addition to the bitwise operation of negation is the use of ^x, C is the use of ~x, the other and the C language is exactly the same.

3) Float type

In the floating-point type, go defines the float32, float64 two, in which float32 equivalent to the Float,float64 in C is equivalent to the double in the C language. At the same time. In go, when defining a floating-point variable, it is assumed that the declaration type is not displayed, and the compiler declares the variable as float64 instead of float32 when it actively calculates it. Like what:

fvalue := 12.0   //这里fvalue有编译器自己主动识别为float64

There is also, in the floating-point number of the inferred equality, due to the accuracy of the floating point number, so can not directly use "= =" to make two of variables inferred. Available in the Math library. Math. Fdim (VAR1,VAR2) to infer the difference of two variables.

4) plural type

The plural type is a new built-in data type introduced in Go. Among them, complex64 is composed of real and imaginary float32, complex128 analogy. The complex number can be used in the following 3 ways:

varcomplex64 = 3.2 + 12ivalue2 := 3.2 + 12ivalue3  complex(3.2, 12real(value1)       //获得复数的实部 i  imag(value1)    //获得复数的虚部

5) string and character types

In go, a string is a built-in type, similar to a package in C + +, and can be used to get characters in the form of an array subscript. Note, however, that it is not possible to change characters in this way. For example, the following methods of use:

var str  string //declares a variable of type string  str  = " string Test " //assignment  ch: = str  [0 ] //gets the value of the first element  length = Len (str< /span>) //the length of the string  str  [ 0 ] =  ' s '  //error XXXX. 

cannot be assigned str = str + " Haha " //string links

It is also important to note that only UTF-8 and Unicode encodings are supported in Golang. There are no built-in encoding conversions for other encodings, so we need to be very careful when we save them. Especially in China. The default save encoding is GBK, which provides a seven cow cloud storage team to make a converted source code: HTTPS://GITHUB.COM/XUSHIWEI/GO-ICONV
The encoding for UTF-8 is defined by a type such as Byte. Unicode is defined by Rune. So pay attention to how the characters are encoded, especially if the range keyword is used when the string is traversed. Then use the form of Rune to traverse. The array value is in the form of byte.

6) array and array slices

The array in Golang and the array in C are, to a certain extent, the same, including the access to the elements from 0 to len-1;
However, the array in Golang has several new features. Contains:
A. Ability to use Len to get the length of an array
B. The ability to use range to traverse the elements in the Access container. Similar to foreach.

for i, v := range array {     fmt.Println("Array element ['', i , '']=", v)}  //两个返回值

C. The array in Golang is a value type, and the array name in the C language represents a different first address. So when you pass an array, the values in the original array are not changed, and the value is passed. So each time it will be worth copy. This significantly reduces the efficiency of function calls and the waste of space. Therefore, the function of array slicing is also provided in Golang.


An array slice (slice) can be thought of as a data structure associated with an array that contains the following three parts:

A pointer to the array it is associated with;
The number of elements in the array in the array slice. (That is, the number of array elements actually contained)
The storage space allocated by the array slice. (How much space is included)
Here are three ways to create an array slice:

/*one: Creating based on Native array */varMyArray[Ten]int=[Ten]int{1,2,3,4,5,6,7,8,9,Ten}varMyslice []int= myarray[: 5]/*second: Create directly with make */MySlice1: = Make([ ]int, 5)//The number of elements in the incident is 5 and all are 0MySlice2: = Make([ ]int,5,Ten)//capacity is tenMySlice3: = []int{1, 2, 3, 4, 5}the//element is a slice of 1,2,3,4,5.

/*third way: 基于已有的切片进行创建*/oldSlice := []int{1, 2, 3, 4, 5}newSlice := oldSlice[:3] // 基于oldSlice的前3个元素构建新数组切片

Operations on array slices:
The Append function is used to append, and the copy function is used for replication.

mySlice2 := []int{8910} // 给mySlice后面加入还有一个数组切片mySlice = append(mySlice, mySlice2...)//注意mySlice2后面的...不能省//等价于:mySlice = append(mySlice,8,9,10)

7) Map

Map is a data type built into Golang, unlike the map in C + + STL, where maps are not sorted according to key-value pairs. (I don't know why, I know readers can tell me why I don't sort.) So isn't it very slow to find? May insert Delete will be faster, this is a trade off?

)
The use of map includes, for example, the following aspects:

A. Declaring and creating, using Map,make Keywords
var map variable name Map[key type] The type of value = Make (type of Map[key) the type of value, element capacity) in which the element capacity parameters can be saved.
Like what:
var myMap map[string] PersonInfo = Make (map[string] personinfo,100)

B. Initialization and assignment
Can be initialized directly when creating a map variable,
MyMap = map[string] PersonInfo {
"1234": personinfo{"1", "Jack", "Box 101, ..."},
}
or assign a value directly to the key:
mymap["1234"] = personinfo{"1", "Jack", "Box 101, ..."}

C. Deletion of elements
Delete the elements within the container directly using the Delete (Map container, key value) function.

For example: Delete (MyMap, "1234");

D. Searching for elements
The map lookup in Golang is directly in the form of an array interview. Like what:
Value, OK: = mymap["1234"]
If OK {//Found
Process the found value
}
You can see that the return value is two, where value is the value of the key of the element to be found, and OK indicates whether it is located.

So finding here can save some of the more logical code used by find in the STL.

Summarize

End Learn the elements of the most important constituent language in Golang, including variables, constants, supported types, and so on.
Below we will learn the Golang syntax of the sentence organization, function, etc.


2015/06/29 by Lingtao in Nanjing
Reprint Please specify:
http://blog.csdn.net/michael_kong_nju/article/details/46425191

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.