Two: Go programming language Specification-type

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

1. Type

A Boolean value that is pre-declared for a numeric value that is named as an instance of a string type. arrays, structures, pointers, functions, interfaces, slices, maps, and channels these composite types can be constructed by type literals.

Each type T has a basic type: If T it is a pre-declared type or type literal, its corresponding base type is T itself. Otherwise, T the base type is the base type of the type in which the type declaration is based.

   string    type T2 T1   type T3 []t1   type T4 T3

The basic type of STRING,T1 and T2 above is string. [The basic type of]T1,T3 and T4 is []T1.

2. Type and value

Note that the following is the same type

      • If two array types have the same element type and the same length, they are of the same type.
      • If the two slice types have the same element type, they are of the same type.
      • If the two struct types have the same field sequence, the corresponding field names are the same, the types are the same, the labels are the same, then they are of the same type. Two anonymous fields whose names are considered the same. The name of the lowercase segment from different packages is always the same.
      • If two pointer types have the same underlying type, they are of the same type.
      • If the two function types have the same number of parameters, the return value is the same, the corresponding parameter type is the same, the return value type is the same, both functions are mutable or immutable, then they are of the same type. parameter and return value names do not need to be matched.
      • If two interface types have the same set of methods, the same name, and the same function type, then they are of the same type. Lowercase method names from different packages are not always the same. Whether the two interface types are the same is independent of the order of the methods.
      • If the two mapping types have the same key value types, they are of the same type.
      • If the two channel types have the same value type and the same direction, then they are of the same type.

3. can be assigned value

      • When x the type and T phase are the same.
      • When x the type V and T has the same base type and at V T least one is not a named type in or.
      • When T it is an interface type and is x implemented T .
      • When a x bidirectional channel value is the same as a T channel type, x type V and element type, and at T V T least one is not a named type.
      • When x The identifier is pre-declared nil and T is a pointer, function, slice, map, channel, or interface type.
      • When x a constant is represented by a value that is untyped, which can be expressed by a type T .

Any type can be given a blank identifier.

4. Boolean type bool

The Boolean type represents the set of Boolean values represented by the pre-declared constants true and false. The pre-declared Boolean type is bool.

5. Numeric type int, etc.

Uint8 all unsigned       8-bit integer sets (0 to 255) uint16      All unsigned 16-bit integer sets (0 to 65535) UInt32      all unsigned 32-bit integer sets (0 to 4294967295) UInt64      All unsigned 64-bit integer sets (0 to 18446744073709551615) int8        all signed 8-bit integer sets (-128 to 127) Int16 all signed       16-bit integer sets (-32768 to 32767) int32       All signed 32-bit integer sets (-2147483648 to 2147483647) Int64       all signed 64-bit integer sets (-9223372036854775808 to 9223372036854775807) float32     All IEEE-754 32-bit floating point set float64 all     IEEE-754 64-bit floating point set complex64   all sets of complex  float32 with complex128 real and imaginary parts Alias        rune Int32 for all complex sets with float64 real and imaginary parts byte uint8        

All numeric types are different except for the alias of Byte Uint8 and the Alias Rune is Int32. Type conversions are required when different numeric types are mixed in an expression or assignment operation. For example, int32 and int are different types, although they may have the same size on a particular schema.

The size depends on the pre-declared numeric type of the implementation:

UINT     32 or 64-bit int      size is the same as uint uintptr  large enough to store an unsigned integer that has no explanatory bit for the pointer value

6. String type

The string is immutable: once created, the contents of the string cannot be changed.

The length of the string s (that is, its byte size) can be obtained using the built-in function Len. If the string is a constant, its length is the compile constant.

The byte of a string can be accessed by an integer 0 to Len (s)-1.

It is illegal to get the address of such an element , and if S[i] is the first byte of a string, &s[i] is invalid.

    " ssssssss "    var Interface {} = x[0]    b:= str. (byte)   // Assertion is byte. If yes then B is the value, if not then panic     FMT. Println (b)

7. Array type

The length of array a can be obtained using the built-in function Len, whose elements can be addressed by an integer subscript 0 to Len (a)-1. Array types are always one-dimensional, but can be combined to form multidimensional types.

[ +]byte[2*n]struct{x, y int32}[ +]*float64[3][5]int[2][2][2]float64//equivalent to [2] ([2] ([2]float64))A:= [3]int{1,2,3}//declares an int array of length 3B:= [Ten]int{1,2,3}//declares an int array of length 10, where the first three elements are initialized to 1, 2, 3, and the other defaults to 0C:= [...]int{4,5,6}//you can omit the length and use the ' ... ' method, go will automatically calculate the length based on the number of elements

8. Slice type Slice

Similar to arrays, slices are indexable and have a length. The length of the slice s can be obtained from the built-in function Len, unlike the array, where the slice can be changed during execution and its elements can be addressed by an integer 0 to Len (s)-1. The slice subscript for a given element may be less than its subscript in its base array.

capacity is the measure of the extension: it is the sum of the length of the slice and the length of the slice's back array, and the slice whose capacity is reached can be created by ' cutting ' a new one from the original slice. The capacity of slice a can be obtained using the built-in function cap (a).

 var  sli2 []int   Sli2  = make ([]int , 20 , 30  ) sli2[ 5 ] = 10   FMT. PRINTLN (SLI2) SLI:  = make ([]int , 5 , 10  ) sli[ 4 ] = 5   FMT. PRINTLN (SLI) Sli3:  = []int  {5 , " Span style= "color: #800080;" >2  } FMT. Println (sli3)  

The results of these two examples are the same slices, since the slices are generated and the arrays are then sliced identically:

Make ([]int, +, +) new ([100]int) [0:50]

A slice is a reference

9. Structure type

A field that is declared by a type without an explicit field name is an anonymous field, also known as an inline field, or an embedding of this type in the structure. This field type must be implemented as a pointer to a type name T or a non-interface type name, and T itself cannot be a pointer type *t.

struct struct {T1//Field name = T1*T2//field named T2P.T3//field named T3*P.T4//field named T4X//T1,*T2,P.T3 with the type of 4 anonymous fields and *p.t4     , y int  //field named X and y}

The following are illegal declarations, because field names must be unique within a struct type:

struct {T     //conflict with anonymous field *t and *p.t *t    //conflict with anonymous field T and *p.t *p.t  //conflict with anonymous field T and *t}

In struct x, if X.F is the legal selector representing the field or method F, the field or method F of the anonymous field is promoted.

Given a struct type S and a T type named, the promoted method contained in the structure method set is as follows:

      • If S an anonymous field T is included, the set of S *S methods with the receiver contains T the promoted method with the recipient. *SThe method set also contains *T the promoted method with the receiver.
      • If the S anonymous field *T is included, the S *S set of methods with the recipient T or *T the promoted method is included.

A field declaration can be followed by an optional string literal that becomes the property of the field in all corresponding field declarations. Annotations can be obtained through the reflective interface, otherwise they will be ignored.

A structure that corresponds to the timestamp protocol cache.//The callout string defines the field number of the protocol cache. struct {microsec  uint64 "Field 1" serverIP6 UInt64 "Field 2" process   String "Field 3"}

10. Pointer type

A pointer type represents a set of pointers to all variables of a given type, called the underlying type of the pointer. The value of the uninitialized pointer is nil.

X:=3y:=&x//y then becomes a pointer to the address FMT that passes X. Println (y, *y)  //*y The value of the address  

Note: * In the above *y represents the value of the pointer in the expression, and in the type definition, a pointer to a type variable

Type Strpoint *stringfunc main () {var strp strpointi: = "a" STRP = &ifmt. Println (STRP)}

11. Function type Func

In go, a function is also a variable, and we can define it by type, which is a type that has all the same parameters and the same return value.

type typeName func (input1 inputType1, Input2 inputType2 [, ...]) (Result1 resultType1 [, ...]) Type Testint func (int)BOOL //declares a function typefunc A (integerint)BOOL {    ifinteger%2==0 {        return false    }    return true}func B (Integerint)BOOL {    ifinteger%2==0 {        return true    }    return false}func filter (slice []int, f testint) []int{//declared function type in this place as a parameter, here can pass a, can also pass B    varresult []int     for_, Value: =Range Slice {iff (value) {result=Append (result, value)}} returnresult}

functions as values and types are very useful when we write some common interfaces, and by the above example we see that the Testint type is a function type, and then the parameters and return values of the two filter functions are the same as the Testint type, but we can implement many kinds of logic, This makes our program very flexible.

The last parameter in the function signature may have a band ... The type of the prefix. A function with such a parameter is called a parameter function and it can accept 0 or more arguments.

Func () func (x int) IntFunc (A, _ int, z float32) Boolfunc (A, b int, z float32) (bool) func (prefix string, values ... int) func ( A, b int, z float64, opt ... interface{}) (success bool)  //for _, N: = range arg   to loop parameter func (int, int, float64) (Floa T64, *[]int) func (n int) func (P *t)

12. Interface type interface

The interface type specifies a set of methods called interfaces. An interface type variable can store any value with a method set type that sets a superset of this interface. This type represents the implementation of this interface. The value of the uninitialized interface type variable is nil.

Empty interface (interface{}) does not contain any method, and because of this, all types implement an empty interface. The null interface does not have any effect on the description (because it does not contain any method), but the null interface is useful when we need to store any type of numeric value, because it can store any type of value.

// define a as null interface var Interface {}varint5S:"HelloWorld"//  A can store any type of numeric value a= = S

A function takes interface{} as a parameter, then he can accept any type of value as a parameter, and if a function returns interface{}, it can return any type of value. is not very useful ah!

13. Mapping Type Map

A mapping is a unique keyset index through another type, which is called a key type. The uninitialized mapping value is nil.

The comparison operator = = and! = must be fully defined by the operands of the key type, so the key type cannot be a function, a map, or a slice. If the key type is an interface type, these comparison operators must be defined by dynamic key values; failure will result in a run-time panic.

The number of elements is called length. For mapping m, the length can be obtained using the built-in function Len and can be changed at execution time. Elements can be added at execution time and retrieved by subscript expressions, and they can also be deleted through the built-in function delete.

varNumbers map[string]intnumbers= Make (map[string]int)//Note is the = numbernumbers["SS"]=5m:= Make (map[string]string) m["Hello"] ="Bonjour"Rating:= map[string]float32{"C":5,"Go":4.5,"Python":4.5,"C + +":2} fmt. Println (rating)

Map is also a reference type, and if two maps point to one level at a time, then one change and the other changes accordingly:

14. Channel Type Chan

The channel provides a mechanism for synchronizing two concurrently executed functions and communicating by passing the value of a specific element type. The uninitialized channel value is nil.

Channels are created using make, but are not referenced. Ensure that each concurrent program (return value) can communicate with the parent environment during the concurrency process

Capacity sets the size of the cache in the channel based on the number of elements. If the capacity is greater than 0, the channel is asynchronous:
If the cache is not full (sent) or non-empty (received), the communication operation is not blocked successfully, and the element is received in the send sequence.

If the capacity is zero or none, communication will succeed only if both the sender and the receiver are ready. The nil channel will never be ready for communication.
The channel can be closed by the built-in function close; The multi-value assignment form of the receive operator tests whether the channel is closed.

CI: = make (chan int) cs: = Do (chan string) CF: = Make (chan interface{})

Channel via operator <- to receive and send data

Ch <-v    //Send V to channel CH.V: = <-ch  //Receive data from CH and assign to V

As an example:

Package Mainimport"FMT"func sum (a []int, C Chanint) {sum:=0     for_, V: =range a {sum+=v} c<-sum//send sum to C}func Main () {a:= []int{7,2,8, -9,4,0} C:= Make (chanint) Go sum (A[:len (a)/2], c) Go sum (A[len (a)/2:], c) x, Y:= <-c, <-c//receive from CFMT. Println (x, y, x+y)}

By default, the channel receives and sends data to be blocked, unless the other end is ready, which makes the Goroutines synchronization much simpler, without the need for an explicit lock. The so-called blocking, that is, if read (value: = <-ch) It will be blocked until data is received. Second, any send (ch<-5) will be blocked until the data is read out. Unbuffered Channel is a great tool for synchronizing between multiple goroutine.

<-The operator specifies the direction, send, or receive of the channel. If no direction is given, then the channel is bidirectional. A channel can be forced to send or receive only by type conversion or assignment.

Chan t          //can be used to send and receive values of type T chan<-float64//can only be used  to send floating-point numbers <-chan int//can      only be used to receive integers

<-The operator is combined with the leftmost chan possible way:

chan<-Chan int    //equivalent to chan<-(chan int) chan<-<-chan int  //equivalent to chan<-(<-chan int) <-chan &L T;-chan int  //equivalent to <-chan (<-chan int) chan (<-chan int)

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.