Golang entry - Data Types

  • Program Entity

        Go to any language program source file consists of a number of entities, then Go language, variables, constants, functions, structures and interfaces are collectively referred to as the "program entities", and their names are collectively referred to as "identifier."

        Identifier can be any alphabetic character unicode encoding that can be represented, numbers and underscore "_." However, the first letter can not be a number or an underscore.


  • Keyword


  • Variables and constants

      Variable using the keyword var, constant use of the keyword const, constants can only be given basic data types themselves

       var num int = 1 // Assignment Initialization

       var num int // declare not only assignment

       var num1, num2 int = 1,2 // parallel assignment

       var (// multi-line assignment

                num1 int = 1

                num2 int = 2

        )


  • Naming the width of an integer

      

      

           1 byte = 8  bit


  • Float

       There are two floating point numbers, and float32 float64, respectively, the space required is 4 bytes and 8 bytes, in the language go, only the relevant portion is represented by floating-point decimal notation, and can not enter the 6 or expressed in hexadecimal system.


  • plural

       There are two types of the same complex, i.e. complex64 and complex128. These two types of storage space required is worth 8 bytes and 16 bytes, respectively, in fact, the value would be represented complex64 type of complex type by a value of two, respectively float32 the real part and an imaginary part. And the type of the value complex128 will represent the real part and the imaginary part of the complex type by the value of two float64 respectively.


  • byte 与 rune

       byte and rune types have one thing in common, namely: they are all type aliases. byte is an alias for uint8 type, and rune alias type is int32.


  • String

     

  • Array

               An array (Array) that can accommodate a plurality of the same type of container elements. The size of the container (i.e., the length of the array) is fixed, and is reflected in the array of the type literal.

               Disclaimer: type myNumbers [3] int // by the keyword type (var), type the name, and literal composition

                len is the name of a built-go language. This type of function is used to obtain the length, it can be used directly go directly language source file.


  • slice
  1. Slice (the Slice) with arrays, the same is also possible to accommodate several types of container elements. Unlike arrays it is unable to determine the length of its worth by the slice type. Each slice values ​​are as array data structures, we put this array is called the underlying array slice.
  2. Slice type literal as: [] int or [] string
  3. Usually the expression slice value strings, arrays or sliced and wrapped by square brackets and a colon ":" separated by two positive integers composition. These two positive integers represent the upper bound of the elements of the lower bound index and element index. Partially "cut down" does not contain an element of index points on the boundary element. Further, the expression evaluates slice would be slice type, and the element type is consistent with the type of element value "slice" of.
  4. In order to obtain the capacity value of the array or slice channel type, we can use the built-in function CAP ();
  5.  Slice type is a reference type. It is the zero value nil, that is a null value. If we just declare a variable of type rather than slice assigned to it, then the value of the variable will benil。
  6. test [1: 4: 4]: The third positive integer which is called the index sector capacity. Its significance is that it can slice the capacity value of the resulting set smaller. In other words, it may limit our access to their more elements of the underlying array through this slice value.
  7.  Although slice value is limited by its capacity in the above-mentioned aspects, but we can be without any restrictions on its extension by another means. This requires the use of built-in functions append. appendIt will be extended slice value and returns a new slice value.
  8. (Slice, 6, 7) the value of a slice of slice = append [] int {2,3,4} becomes a [] int {2, 3, 4, 6, 7}, once extended beyond the slicing operation is operated capacity value, then the underlying array slice will be replaced automatically. This also makes the method more stringent access control by setting the upper bound of the capacity of its index to the underlying array.
  9. copy():The function takes two values of the same slice type as a parameter, and will copy the second parameter value corresponding to the position of the element (the same as the index value) on the first parameter value. There are two points to note: 1. this minimal replicon replication follow principles, namely: the number of elements to be copied is always equal to the length of the shorter length of the parameter value. 2. the appendfunction is different copyfunction directly modify the first parameter value thereof.
  • dictionary
  1. Go language dictionary (Map) type is actually a hash table (Hash Table) is a realization. Dictionary used to store key-value pairs of unordered collection. The same dictionary keys are unique. If the key placed in the same name, the value associated with this key is replaced.
  2. Literal: map [K] T // K for the type of bond, T is worth a specific type is declared as: map [int] string dictionary of key type must be comparable, otherwise it will cause an error. In other words, it can not be sliced, dictionary, function types, the value for the dictionary, the index expression to fetch keys If there is not, then it's null value type (also known as the default value) as a result of the evaluation index expression. Because the string Null type "",与切片类型相同,字典类型属于引用类型,它的零值为nil.
  3. Dictionary Initialization: mm: = map [int] string {1: "a", 2: "b", 3: "c"}
  4. Assignment: the specified key assigned to mm [2] = "bb" 2 corresponding to the key value is replaced with "bb"
  5. Add: mm [4] = "" new key-value pair added 4: ""
  6. Value determines whether there is key: e, ok: mm [5] ok type bool ok "present":? "Absent"
  7. Delete key: delete (mm, 4) // there is no deletion is not operating
  • aisle
  1.  Channel (Channel) is a very unique Go language data structure. It can be used for data transfer between types of different Goroutine, and concurrently secure. In contrast, the data types that we introduced earlier are not concurrent safe. This requires special attention.
  2.  Goroutine (also known as Go program) can be viewed as a carrier carrying the code block may be executed concurrently. It is scheduled by the runtime system in Go, and relying on the operating system threads (also known as kernel threads) to concurrently execute wherein the code block. As for how to write this block of code and how to drive this block of code execution.
  3. Disclaimer: chan T // chan为关键字,while the right is the representative of the channel type allows transfer of types of data (also known as the element type channel)
  4. Initialization: make (chan int, 5) // makefunction may also be used to initialize the value of a dictionary or a slice type. Length of the channel should be referred to the value of its buffer size. In other words, it represents the number of channels may be temporarily stored in the value data. Note that the channel is temporarily stored in FIFO data values, i.e.: sooner be placed (or transmit) a data channel to the first value may be taken out (or received).
  5. Initialization: ch1: = make (chan string, 5)        
  6. Send: ch1 <- "value1" // channel to ch1send the string"value1"
  7. Receiving: value, ok: = <- receiving operation ch1 // channel may also have a second value bool value result, the same purpose of this is to eliminate ambiguity associated with a zero value. Here the variable okvalues are the same booltype. It represents the state of the channel values, truerepresents the effective channel value, and falserepresents the value of the channel has been ineffective (or closed). The deeper reason is that, if received before or during the operation of channel values is closed, the receiving operation will end immediately and returns a zero value element is the type of channel values. According to a first written above, we can not determine what reason the received zero value Yes. However, with the results after the second value, such judgments do just fine.
  8. Close: close (ch1) // Note that the value of the channel is closed will lead to repeated run-time panic. This causes the program to crash. So be sure to avoid this from happening. Further, in the effective channel value prerequisite for its action at the transmission channel value is full (wherein the number of buffered data has become equal to its length) is blocked. Has been transmitted to a data value of closed channels cause panic runtime. On the other hand, a reception operation for a valid channel values will be blocked when it is empty (no data wherein no cache). In addition, there are rules relating to transmission and reception operations with several channels. But here we remember these three above it. Finally, the slices and the same type of dictionary, the channel type is a reference type. Its value shall be zero nil.
  9. 8 above said channel buffered, or simply a buffer channel. Channel has buffered and unbuffered points. As we have said, it can be cached in the buffer channel N data. We have to specify this initialization value when a channel N. In contrast, non-buffered channel does not cache any data. The sender will immediately be blocked when sending data to the channel value until one of the reception side from the reception of the channel values ​​of this data.
  10. Unbuffered channel initialization: make (chan int, 0)
  11. We also to transmit the data in the channel direction is divided based on the channel. By default, the channel is bidirectional, that is, two-way channel. If only one-way data transmission channel, then the channel will be referred to as a one-way channel. We can not specify it in the initialization value when a channel is unidirectional.                               
    接收通道:type Receiver <-chan int 
    发送通道:type Sender chan<- int 

    The main constraint is the one-way passage way uses channel values. For example, we give it a send channel as an argument when you call a function, in order to constrain it can only send data to the channel. As another example, a function will return a result as a receiving channel, in order to restrain the function calling code can only receive data from this channel. It belongs to the category of API design.

  • function

        However, in Go, the function is the number (first-class) type. This means that we can function as a value to pass and use. Such a process represents a function: it accepts several input (parameter), and after performing steps (statements) return output (result). In particular, the Go language function can return multiple results.

func(input1 string ,input2 string) string
函数类型的字面量由关键字func、由圆括号包裹参数声明列表、空格以及可以由圆括号包裹的结果声明列表组成。
  • Structures and methods
  1. Structure (struct)

           Structure type (Struct) Go language is more flexible than the type of function. Which encapsulates attributes and operations. The former type of structure that is in a field, and the latter method has a structure type.

type Person struct {     //结构体
    Name   string
    Gender string
    Age    uint8
}   

p := struct {           //匿名结构体
    Name   string
    Gender string
    Age    uint8
}{"Robert", "Male", 33}

          Type of structure comprising a plurality of fields and methods of the equivalent object attributes and operations packaged together. Note, however, the object is different, can not exist inheritance relationships between structure type (as well as any type).

package main

import "fmt"

type Person struct {
    Name    string
	Gender  string
	Age     uint8
	Address string
}

	func (person *Person) Move(str string) string {
        old := person.Address
        person.Address = str
        return old
	}
	
func main() {
	p := Person{"Robert", "Male", 33, "Beijing"}
	
	oldAddress := p.Move("San Francisco")
	

	
	fmt.Printf("%s moved from %s to %s.\n", p.Name, oldAddress, p.Address)
}
  • interface

        In the Go language, interface type always represents a certain type (that is, all the realization of its type) behavior. An interface type declarations often contain keywords type, type name, keywords interfaceand statements by a number of methods wrapped in curly braces.

type Animal interface {
    Grow()
    Move(string) string
}
  • pointer

       When the address operator &, when applied to a pointer value will be taken for this value, and when the address operator *will remove that when the value of the pointer is applied to a pointer value. They can be considered the opposite of operations.

       Recipient identifier method is represented by a copy of that value which currently belongs, rather than the value itself.

        Type has a pointer to its method and all its base type as the receiver type, but only the type of substrate and its method has its own type of receiver.

Published 47 original articles · won praise 3 · Views 7887

Guess you like

Origin blog.csdn.net/qq_38228582/article/details/104000690