Types and data structures in the Go language

Source: Internet
Author: User

This chapter mainly describes how to define variables, constants, go built-in types, and some techniques in go programming

Defining variables

There are many ways to define variables in go:

  1. Using the var keyword is the most basic way to define a variable, somewhat different from the C language, as follows:
    var variable_name type
  2. Define multiple variables
    var name1,name2,name3 type
  3. Define variables to initialize at the same time
    var name1 string = "Liming"
  4. Simultaneous initialization of multiple variables
    var Name1,name2,name3 string = "A", "C", "D"
  5. Initialize directly ignoring type at the same time
    var name1,name2,name3 = "A", "C", "D"
  6. Most simplified, only applicable to function internal use, global variables can not be used, or error
    Name1,name2,name3: = "A", "C", "D" constants

    A constant is a determined value that cannot be changed. (Can be a Boolean value, can be a string, numeric, and other types)
    The syntax is as follows:
    Const name TYPE = value

    Built-in base type (focus on Rune, Byte, String type)

    Three built-in text types in the Go language: String, (bytes) byte, (rune) Rune

  7. Boolean type
    It has a value of only ture and false, which is false by default. Defined as follows:
    var a bool
  8. Numeric type
    There are two types of symbols and no symbols. Both int and UINT are supported. These two types are the same length. However, the exact length is determined by the compiler.
    Go also has a direct definition of the number of digits of the type: Rune,int8,int16,int32,int64 and Byte,uint8,uint16,uint32,uint64.
    Where Rune is the alias of Int32, and Byte is the alias of Uint8. specifically visible official website.
    It is important to note that different types of variables are not allowed to be assigned to each other and operate, otherwise the compilation will error.
    There are two types of floating-point numbers, float32 and float64, the latter by default.
    Plural: The default type is complex128 (64-bit real number + 64-bit imaginary number). and a complex64.
    var c complex64 = 6+5i//6 is the real part, 5 is the part of the imaginary number, and I is the unit of imaginary numbers.
    Fmt. PRINTF ("value is:%v", c)
  9. String
    The string used in Go is utf-8 character set encoding. Double or inverted quotation marks are assigned. You can use the escape character in double quotes, which is what you see in an inverted quote.
    var a string = "you"
    In the go language, the characters in the string are immutable, otherwise the compilation will error: cannot assign to s[0]
    var s string = "Hello"
    S[0] = ' C '
    But in practice it will be applied to the change string, which can be rune or byte with a flexible approach. Because the string type is stored in go in a byte array, it is not stored as a character.
    s:= "Hello"
    C:=[]rune (s)//This can also be turned into a byte array.
    C[0]= ' C '
    S1:=string (c)
    Fmt. Println (S1)
    You can also make changes to one of the characters in a string by slicing the way
    s: = "Hello"
    s = "C" + s[1:]
    Fmt. Println (S, s[2])
    Action string:
    S1,s2,s3:= "I", "AM", "studying"
    S4:=s1+s2+s3
    Fmt. Println (S4)
  10. Type of error
    The error type is the built-in type of go. Specifically used to handle error messages. The go package also has a special packet errors to handle the error:
    ERR: = errors. New ("Emit macho dwarf:elf header corrupted")
    If err! = Nil {
    Fmt. Print (ERR)
    }go storage at the bottom of the data
  11. The underlying type is allocated a chunk of memory, and the corresponding values are stored in the allocated memory:

    Even though I and J have the same memory layout, they has different types:the assignment i = j is a type error and must Be written with an explicit conversion:i = Int (j)
    Through, we can learn that i,j,f is in a memory layout. This sentence is a bit confused. float32 Although it has the same memory footprint as int32, it is in a different memory layout.
      1. struct type
        Type point Struct{x,y int}//defines a struct that assigns a value to the variable p and pp.

        For a struct type, it is a type that a user can customize, which is actually a new type that is synthesized with other type groups
        How to define:
        Type Variable_type_name struct{
        Member1 type
        Member2 type
        Member3 type
        ...
        }
        Declare the type of the variable, as follows, Variable_name is a variable_type_name type, and assigns a value
        Variable_name: = variable_type_name {value1,value2,value3,...}
        Of course, you can also assign values to members in the following ways.
        Variable_type_name.number1=value1
        In structs, the memory that a member occupies is also one after another continuous. If the memory in PP and P is not in the same contiguous memory address, one point is the address of 10 and 20, one is the representation of 10 and 20
        Can also be understood by
      1. String type

        As we can see from the above figure, the string is represented in memory as occupying 2-word, containing a pointer to the character data and a string length.

        As we can see from the above results, it is safe to change an element of the underlying array at all.
        Because The string is immutable, it's safe for multiple strings to share the same storage, so slicing s results in a new 2-word structure with a potentially different pointer and length, still refers to the same byte sequence.
        Because of its underlying immutability, if slice is used, it can cause unnecessary waste (because the underlying array is preserved as long as it is useful to slice). In general, avoid using slice in strings in most languages.
    • 4.slice

      Slice the actual underlying is an array, which is defined by [] or make. In memory it is a 3-word structure consisting of PTR (a pointer to the first element of the array), lenth, and capacity. Len is the index of the slice in the line want X[i], and the cap is the slice capacity of the line x[i;j],copy is used for copying, copy (S1,S2)
      The slice string or array is not a copy, it simply creates a new structure that contains the PTR, Len, cap
      , the bottom of it is no change, such as.
      Because slices is multiword structures, not pointers, the slicing operation does no need to allocate memory, not even FO R the slice header, which can usually is kept on the stack. This representation makes slices about as cheap to use as passing around explicit pointer and length pairs in C. Go originally represented a slice as a pointer to the structure shown above, but doing so meant that every slice operation Allocated a new memory object. Even with a fast allocator, which creates a lot of unnecessary work for the garbage collector, and we found that, as is th e case with strings above, programs avoided slicing operations in favor of passing explicit indices. Removing the indirection and the allocation made slices cheap enough to avoid passing explicit indices in most cases
    • 5.map Type
      Its structure is a hashtable, the specific explanation can refer to the source code:
      $GOROOT/src/runtime/hashmap.go
      Only part of the interception, you can see in detail.
      //a map is just A hash table. The data is arranged
      //to an array of buckets. Each bucket contains up to
      //8 key/value pairs.
      Description given by the official:
      A Map is an unordered group of elements of one type, called the element type, indexed by A set of unique K Eys of another type, called the key type. The value of an uninitialized map is nil
      The map type is a reference type, and it modifies the key value that may modify the underlying hashtale, similar to slice (reference type). As follows:

      the comparison operators = = and! = must is fully defined for operands of the key type; Thus the key type must n OT be a function, map, or slice. If The key type is a interface type, these comparison operators must be defined for the dynamic key values; Failure would cause a run-time panic.
      Refer to document here:
      http://blog.csdn.net/slvher/article/details/44340531
      Go Source code-src/pkg/runtime/hashmap.c
      Https://golang.org/ref/spec#Map_types

The map type is similar to a dictionary in Python. is actually a collection of key-value pairs. The syntax format is as follows:
Declare variable, default map is Nil,nil map cannot be directly assigned, default is 0
var map_variable_name map[key_data_type]value_data_type
Use the Make function to create a non-nil map because nil map cannot hold key-value pairs.
Map_variable_name = Make (Map[key_data_type]value_data_type,cap)
Concise: Map_variable_name: = Map[key_data_type]value_data_type{k1:v1,k2:v2,....}
Here are two examples of definitions

The cap above can be omitted, but it is best to set it in time, why?
If the value of the Key-value key is out of capacity, the capacity is automatically expanded (since each expansion is a reallocation of memory and copy)
The key in the map is unique.
Use Len () to get the number of elements
Use Delete () to manipulate the deletion of key-value pairs
Delete (Key,value)//note cannot be nil map, otherwise an exception panic will be thrown.
Use For....range to iterate over the map.
Map reads and sets are similar to slice, with key to operate, but different, the map key can be int, string, float (preferably not float) (as long as the support = = or! = type can be, here function, map, Slice is not supported, and the index in slice can only be of type int. Value can be any other type.
Map lookups are faster than linear searches, but are much slower than the type of data accessed using the index (said to be 100 times times slower).
Attention:
1) The element in map is not a variable and therefore cannot be addressed. The reason for this is that the map may reallocate more memory space as the elements increase, and the old values will be copied to the new memory space, so the previous address will be invalidated.
2) The For...range traversal is used in map, (that is, you cannot get the key value by using an index, but you can reassign it) and its iteration order is indeterminate, that is, the order in which each result is executed may be different. In the go language is intentionally so designed, is for example to avoid the program relies on some kind of hash implementation, the purpose is for the program's robustness. If you do not want to traverse sequentially, you must display the sort key, and you can use the string function in the sort package. The code below is generally best not to use this way.
Import "Sort"
var names []string
For, Name: = Range Ages {
names = append (names, name)
}
Sort. Strings (names)
for
, Name: = range Names {
Fmt. Printf ("%s\t%d\n", Name, Ages[name])
}
If the key is not present in map, the return value is 0, but what if the key exists and the key value is 0?
Map function Lookup:
Value, OK: = map["1"]
If ok{
Processing the value values found
}

    • 6.0 value
      A value of 0, not a null value, but a default value when the variable is not assigned, typically 0
      int int8 int32 Int64 0
      UINT 0x0
      Rune 0//actual is Int32
      BYTE 0x0//actual is Uint8
      float32 float64 0
      BOOL False
      String ""
      Reference Documentation:
      Https://research.swtch.com/godata
      Https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.2.md
      http://blog.csdn.net/slvher/article/details/44340531
      Go Source Code-src/pkg/runtime/hashmap.c
      Https://golang.org/ref/spec#Map_types

Types and data structures in the Go language

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.