Golang Notes 1 Basics, basic data types

Source: Internet
Author: User

First, Go Language Foundation

1. Basic

Identifiers in the go language must begin with a letter (Unicode letter, Php/js can be used as the variable name in Chinese). Capital letters are different from lowercase letters: Hello and hello are two different names.
There are 25 keywords in go:

break    default     func   interface selectcase     defer       go     map       structchan     else        goto   package   switchconst    fallthrough if     range     typecontinue for         import return    var

If a name is defined in the function content, then its scope is in the function content, if defined outside the function, it will be accessible in all files of the current package. The case of the initial letter of the name determines the visibility of the name outside the package. If a name starts with a capital letter, it can be accessed by an external package, such as the printf function of the FMT package.

2. Notes

    • Single-line comment//...
    • Multiline Comment/* ... */

3. General structure of Go program

    • Go programs are organized through the package
    • Only packages with a package name called Main can contain the main function
    • One executable program has and only one main package
// 当前程序的包名package main// 导入其他的包import "fmt"// 一次导入多个包import (    "io"    "os")// 常量的定义const PI = 3.14// 全局变量的声明与赋值,该变量在整个package中使用var name = "go"// 一般类型声明type newType int// 结构的声明type go struct{}// 接口的声明type golang interface{}// 由main函数作为程序入口启动func main() {    fmt.Println("Hello World!")}
    • If the imported package does not use a type or function, it will report a compilation error
    • Package alias: Import io "FMT" This allows the FMT to be set to an IO, which can be called: IO. Println ("...")

4. Visibility rules

The go language uses casing to determine whether the constant, variable, type, interface, struct, or function can be called by an external package: according to the Convention, the first letter of the function name is private (external cannot be called), uppercase is public

II. Basic data types

1. Variables and Constants

    • Normal Assignment:
// var 变量名称 变量类型 = 值var num int = 1
    • Assign values in parallel
var num1,num2 int = 1, 2
    • Multi-line Assignment
var (    num1 int = 1    num2 int = 2)

2. Name and width of integer type

Go's integer type a total of 10
There are two integer types that are related to the computed schema: signed integer type int, unsigned integer type UINT.
On computers with different computing architectures, the widths they embody (the space required to store values of a type) are not the same. The unit of space can be a bit or byte.

In addition to these two computed-schema-related integer types, there are 8 integer types that can explicitly express their own widths:

3. Notation for integer type values

If you assign a value to the variable num with 8 binary:

num = 039 // 用"0"作为前缀以表明这是8进制表示法

If you assign a value to the variable num with 16 binary:

num = 0x39

4. Floating-point number type

There are two floating-point number types: The value of the Float32/float64 floating-point type is usually the integer part, the decimal point "." and fractional components. Another way to represent this is to add an exponential portion to it. The exponential portion is represented by the "E" or "E" and the signed 10-in integer. Example: 3.9E-2 represents floating point number 0.039. 3.9E+1 indicates floating point number 39.
Sometimes floating-point type values can also be simplified. For example, 39.0 can be reduced to 39.   0.039 can be simplified to. 039. The relevant part of the floating point in go can only be represented by the 10 binary notation.

5. Plural type

There are two types of complex numbers: complex64 and complex128. In fact, the value of the complex64 type represents the real and imaginary parts of the complex number, respectively, by the values of the two float32 types. The value of the complex128 type is represented by a value of two float64 types representing the real and imaginary parts of the complex number.
The value of a negative type is generally composed of the real part of the floating-point number, the plus sign "+", the imaginary part of the floating-point representation, and the lowercase letter "I", such as 3.9E+1 + 9.99e-2i.

6, Byte and rune

Both byte and Rune belong to the alias type. Byte is the alias type of uint8, and Rune is the alias type of Int32.
A rune type value can represent a Unicode character. A Unicode code point is typically represented by "u+" and an integer represented in hexadecimal notation, such as the Unicode code point for the English letter ' A ' as "u+0041".
The value of the Rune type needs to be wrapped by a single quote "'", but we can also express it in several other ways:

In addition, several special sequences of characters are supported in the representation of the Rune type value, namely: Escape character. Such as:

7. String type

There are two representations of the string, namely, the native representation and the explanatory notation. In native notation, the character sequence needs to be wrapped with an inverted quotation mark "'", and if interpreted notation is used, the sequence of characters is enclosed in double quotation marks "" ".

var str1 string = "str"var str1 string = `str`

The difference between the two is that the former represents the WYSIWYG (except the carriage return). The latter represents a value in which the literal character will work. The string value is immutable, and if we create a value of this type, it is impossible to make any modifications to it itself.

Third, advanced data types

1. Array type

An array is a container that can hold several elements of the same type. The length of the array is fixed. Declare an array type as follows:

type MyNumbers [3]int

A type declaration statement consists of a keyword type, a type name, and a type literal

Above this type declaration statement is actually an array type [3]int declares an alias type.] This allows us to use mynumbers as an array type [3]int.
We represent the value of such an array type when. The type literal should be written to the leftmost, and then wrapped in curly braces to enclose several elements of that value, separated by commas (half-width), namely:

[3]int{1,2,3}

Now let's assign this array literal to a variable named numbers:

var numbers = [3]int{1,2,3}

This is a variable declaration statement that assigns a value to a variable while declaring it

Another way is to omit an array representing its length in the type literal, for example:

var numbers = [...]int{1,2,3}

You can access any one of the elements in the variable in the following way. Cases:

numbers[0]numbers[1]numbers[2]

If you want to modify one of the element values in an array value, you can:

numbers[1] = 4

You can get the array length in the following ways:

var length = len(numbers)

If an array is not assigned a value, its default value is [length]type{0,0,0 ...}

2. Slice type

(1) Basic

Slices (slice) are also containers that can have several elements of the same type as arrays. Unlike arrays, the length of the slice type is indeterminate. Each slice value will use the array as its underlying data structure. The literal representation of the slice type is as follows:

[]int

Or is:

[]string

The declaration of a slice type can be this:

type MySlice []int

The representation of the slice value is also similar to the array value

[]int{1,2,3}

The method of manipulating array values also applies to slice values. There is also a way to manipulate an array called "slices," and the way to implement a slice is to slice the expression. Cases:

var number3 = [5]int{1,2,3,4,5}var slice1 = numbers3[1:4]

The result of the slice expression Numbers3[1:4] in the example above is that []int{2,3,4} is clearly tangent to the element that does not contain the upper-bound index of the element. Actually slice1 the underlying array of this slice value is the value of Number3.
We can also perform slice operations on slice values:

var slice2 = slice1[1:3]

In addition to the length slice value and the array value there is another property--capacity. The capacity of an array is always equal to its length, and the size of the slice value is often different from its length. Such as:

, the capacity of a slice value is the absolute value of the index value of its first element value in its underlying array and the difference between the length of the array. You can use the CAP () built-in function to get the capacity of the array, slice, and channel type values:

var capacity2 int = cap(slice2)

The slice type belongs to the reference type, and its 0 value is nil, which is the null value. If we only declare a slice type and not assign a value to it, then its default value: nil.

(2) More ways to do slices

Sometimes we can put a third positive integer in square brackets. As shown in the following:

numbers3[1:4:4]

The third positive integer is the upper-bound index of the capacity, which means that the capacity of the slice value as a result can be set to a smaller size. It can restrict access to more elements in its underlying array through this slice value. The assignment statements for NUMBERS3 and slice in the previous section are as follows:

var numbers3 = [5]int{1,2,3,4,5}var slice1 = numbers3[1:4]

At this point, the value of the variable Slice1 is []int{2,3,4}. However, we can extend the length of the same as its capacity by doing the following:

slice1 = slice1[:cap(slice1)]

With this action, the value of the variable slice1 changes to []int{2,3,4,5}, and its length and capacity are all 4. The elements in the (1,5) range of the index values in the NUMBER3 value are now reflected in the value of Slice1. This is premised on the underlying array where the value of Number3 is the value of Slice1. This means that we can easily access more elements in their underlying array that are larger than the corresponding index values. If we write a function that returns such a slice value, then the program that gets it is likely to have access to elements that should not be exposed to it.
If we add a third index (that is, the upper-capacity index) to the slice, such as:

var slice1 = numbers3[1:4:4]

After that, we will not be able to access the Fifth element in the value of Number3 through Slice1.
Although the slice values are limited by their capacity in these respects. But we can extend it in an unrestricted way by another means. This requires the use of the built-in function append. Append expands the slice value and returns a new slice value, using the following method:

slice1 = append(slice1, 6, 7)

By doing this, the value of Slice1 becomes []int{2,3,4,6,7}. Once the expansion operation exceeds the capacity of the slice value being manipulated, the underlying array of the slice is replaced with the last action slice as "copy". The operation is implemented by invoking the copy function. The function receives two of the same slice values as parameters and copies the elements in the second parameter value to the corresponding position in the first parameter value (the index value is the same). Here are two points to note:

    1. This replication follows the principle of minimal replication, that is, the number of elements being copied is always equal to the length of the shorter parameter.
    2. Unlike the Append function, the copy function directly modifies its first parameter value.

Cases:

var slice4 = []int{0,0,0,0,0,0}copy(slice4, slice1)

With the above copy operation, Slice4 will become []int{2,3,4,6,7,0,0}.

3. Dictionary type

The dictionary (MAP) type of the go language is the implementation of a hash table. The literal number of the dictionary type is as follows:

map[K]T

where "K" is the type of the key, and "T" represents the type of the element (value). If we describe a dictionary type with a key type of int and a value type of string:

map[int]string

The key type of the dictionary must be comparable, otherwise it will cause an error, i.e. the key cannot be a slice, dictionary, function type

The literal representation of a dictionary value is actually similar to the literal representation of an array's slices. The leftmost is still the type literal, and the right side is enclosed by curly braces and has a comma-separated key-value pair. The keys and values for each key-value pair are separated by colons. Take the dictionary type map[int]string as an example. The literal amount of his value can be this:

map[int]string{1:"a",2:"b"m,3:"c"}

We can assign this value to a variable

mm := map[int]string{1:"a",2:"b",3:"c"}

Use an index expression to remove a value from the dictionary:

b := mm[2]

You can assign a value with an index expression:

mm[2] = b + "2"

The value of the MM medium key of 2 becomes "B2". You can add a key-value pair to the dictionary in the following ways:

mm[4] = ""

For dictionary values, if the specified key does not have a corresponding value, the default is a null value of that type. So Mm[5] will return a "". But in that case we don't know if mm[5] is "or mm[5" without this value. So go provides another way to do this:

e, ok := mm[5]

The index expression for a dictionary can have two job search results, and the second job search result is of type bool.   It is used to indicate whether a specified key-value pair exists in the dictionary value. The way to remove a key-value pair from a dictionary is simply to call the built-in function Delete:

delete(mm, 4)

Delete is deleted regardless of whether there is a key-value pair with a key of 4 in MM. The dictionary type belongs to the reference type, and its 0 value is nil

4. Channel Type

Channel is a very unique data structure in the go language. It can be used to pass typed data between different goroutine. and is concurrency-safe. In contrast, several previous data types are not concurrency-safe.
Goroutine can be seen as a vector that hosts code blocks that can be executed concurrently. They are dispatched by the run-time system of the go language and are executed concurrently by the operating system thread (also known as the kernel thread) to execute the code block.
The method of representing the channel type is simple and consists of only two parts:

chan T

In this type literal, the left side is the keyword Chan representing the channel type, and the right side is a mutable part that represents the type of data that the channel type allows to pass (or the element type of the channel).
Unlike other data types, we cannot represent a value for a channel type, so we cannot assign a value to a variable of a channel type by literal means. The purpose can only be achieved by invoking the built-in function make. The make parameter accepts two parameters, the first parameter is the literal of the type that represents the value to be initialized (example: Chan int), and the second parameter is the length of the value, for example, if we want to initialize a channel value with a length of 5 and an element type of int, you need to write:

make(chan int, 5)

The Make function can also be used to initialize the value of a slice type or dictionary type.
The data in the channel value is pre-FIFO. Below, we declare a variable of a channel type and assign it a value:

ch1 := make(chan string, 5)

In this way, we can use the Accept operator <-to send data to the channel value. Of course, it can also be used to receive data from the channel value, for example, if we want to send the string "value1" to the channel CH1, then we should do this:

ch1 <- "value1"

If we receive the string from CH1, this is the case:

<- ch1

We can assign the accepted string to a variable, such as:

value := <- ch1

As with index expressions for dictionary values, an accept operation on a channel value can have a second result value:

value, ok := <- ch1

The OK value here is of type bool. It represents the state of the channel value, true means that the channel value is valid, and False indicates that the channel value is invalid (or closed), and the deeper reason is that if the channel value is closed before or during the accept operation, the receive operation ends immediately and returns a 0 value of the element type of the channel value.
You can close a channel by using the function close:

close(ch1)

A duplicate shutdown of the channel value throws a run-time exception that causes the program to crash. If the channel value is valid, the send operation against it is blocked when the channel value is full (where the number of cached data is equal to its length). Sending data to a channel value that has been closed throws a run-time exception. A receive operation on a valid channel value is blocked when it is already empty. The channel type is a reference type and its 0 value is nil.

5, more types of channels

The channel in the previous section is actually just one of the channels in go. is a buffered channel, or simply a buffer channel.
The channel is buffered and non-buffered, the buffer channel can cache n data, we initialize a channel value must be specified when the n,** relative non-buffered channel does not cache any data, the sender when sending data to the channel is immediately blocked. Until one of the receivers has received this data from that channel. * * The initialization method for non-buffered channel values is as follows:

make(chan int, 0)

In addition to the above classification method, we can also divide the channel according to the data transmission direction in the channel. By default, channels are bidirectional, which is two-way communication. If the data can only be transmitted in one direction in the channel, then the channel is called a one-way channel. We cannot specify one-way when initializing a channel value. However, when writing a type declaration, you can:

type Receiver <- chan int

Type receiver represents a one-way channel type from which data is received only, and such a channel is also known as a receive channel. The receive operator <-on the left side of the keyword Chan represents the flow of data. Correspondingly, if we want to declare a send channel type, then this should be the case:

type Sender char <- int

This time the <-was placed on Chan's right, and the arrows pointed to the channel. We can assign a bidirectional channel to a variable of the above type, just like this:

var myChannel = make(chan int, 3)var sender Sender = myChannelvar receiver Receiver = myChannel

But the reverse is not possible:

var myChannel1 chan int = sender

The function of one-way channel is to constrain the way the program uses the channel value, for example, when we call a function, we give it a send channel as a parameter, so as to constrain it to send data to that channel only. Another example is a function that returns an accepted channel as a result, which constrains the code that invokes the function to receive data from this channel only.

218 Reads
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.