Golang type System Notes

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

One, constant:
Const Pi float64 = 3.14159265358979323846
Const ZERO = 0.0//No type floating-point constant
Const (
Size Int64 = 1024
EOF =-1//no type integral constant
)
Const U, v float32 = 0, 3//U = 0.0, v = 3.0, constant multiple assignment
Const A, b, C = 3, 4, "foo"

The Go language pre-defines these constants: "true", "false", and "iota".
Iota is special and can be thought of as a constant that can be modified by the compiler, which is reset to 0 when each const keyword appears, and then, before the next const appears, each time a iota is present, the number it represents is automatically increased by 1.
The following example can be used to understand the usage of iota basically:
Const (//Iota reset to 0
C0 = Iota//C0 = = 0
C1 = IOTA//C1 = = 1
C2 = Iota//C2 = = 2
)

Third, enumeration:
Const (
Sunday = Iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Numberofdays//This constant is not exported, because he is a lowercase start, only within the package is visible
)

Four, the integral type: Since the integral type has the platform correlation, still is less uses the int uint to be better.

Type length (bytes) value range
Int8 1? 128 ~ 127
Uint8 (i.e. byte) 1 0 ~ 255
Int16 2? 32 768 ~ 32 767
UInt16 2 0 ~ 65 535
Int32 4? 2 147 483 648 ~ 2 147 483 647
UInt32 4 0 ~ 4 294 967 295
Int64 8? 9 223 372 036 854 775 808 ~ 9 223 372 036 854 775 807
UInt64 8 0 ~ 18 446 744 073 709 551 615
Platform related to int platform
Platform related to UINT platform
UIntPtr with 4 bytes on 32-bit platform and 8 bytes for 64-bit platforms

Five, floating-point type:

The go language defines two types of float32 and float64, where float32 is equivalent to the float type of C, and float64 is equivalent to the double type of the C language.
In the go language, the code that defines a floating-point variable is as follows:
var fvalue1 float32
Fvalue1 = 12
Fvalue2: = 12.0//If the decimal point is not added, the fvalue2 is deduced as an integer instead of a floating-point type
Floating-point comparison:
Because floating-point numbers are not an exact representation, it is not feasible to use = = as an integer to determine whether two floating-point numbers are equal, which can lead to unstable results. The following is a recommended alternative:
Import "Math"
P for user-defined comparison accuracy, e.g. 0.00001
Func isequal (F1, F2, p float64) bool {
return Math. Fdim (F1, F2) < P
}

Six, "string"

Disclaimer: Var str string
str = "Hello"
Or: str: = "Hello"

Action: ch: = str[0]//Take the first character of a string

The contents of the string cannot be modified after initialization: str[0] = ' X '//Compile Error

x + y string Connection "Hello" + "123"//result is Hello123
Len (s) string length len ("Hello")//result is 5
S[i] Take the character "Hello" [1]//result is ' e '

For more string manipulation, Golang standard library strings package.

Seven, array:
Declaration: The following are some general methods of array declaration:
[32]byte//32-length array with one byte per element
[2*n] struct {x, y Int32}//Complex type array
[1000]*float64//pointer array
[3] [5]int//two-D array
[2] [2] [2]float64//equivalent to [2] ([2] ([2]float64)]

Cycle:
For I: = 0; I < Len (array); i++ {
Fmt. Println ("Element", I, "of array is", Array[i])
}
For I, V: = range Array {
Fmt. Println ("Array element[", I, "]=", V)
}

"★ Value Type" All value-type variables produce a copy action when they are assigned and passed as arguments. If you use an array as the parameter type for a function, the parameter will occur when the function is called for data replication.
It is important to note that in the go language an array is a value type. Therefore, the contents of the incoming array cannot be modified in the body of the function, because the functions inside the function are only
A copy of the incoming array.


Eight, array slicing (slice)

Statement:
Create an array slice based on an array var myslice []int = Myarray[:5]
Create an array slice based on all elements of MyArray: Myslice = myarray[:]
Creates an array slice with an initial element number of 5, with an element initial value of 0:myslice1: = Make ([]int, 5)
Create an array slice with an initial element number of 5, an element with an initial value of 0, and a storage space of 10 elements: MySlice2: = make ([]int, 5, 10)
Directly creates and initializes an array slice with 5 elements: mySlice3: = []int{1, 2, 3, 4, 5}

Array slices support the go language built-in cap () function and the Len () function, and listing 2-2 simply demonstrates the use of these two built-in functions.
As you can see, the CAP () function returns the amount of space allocated by the array slice, and the Len () function returns the number of elements currently stored in the array slice.

To add an element:
Myslice = Append (Myslice, 1, 2, 3)

MySlice2: = []int{8, 9, 10}
Add another array slice back to Myslice
Myslice = Append (Myslice, MySlice2 ...). Note that three points are required ...

Copy array slices: slice1: = []int{1, 2, 3, 4, 5}
Slice2: = []int{5, 4, 3}
Copy (Slice2, Slice1)//Only the first 3 elements of Slice1 are copied to Slice2
Copy (Slice1, SLICE2)//Only 3 elements of Slice2 are copied to the first 3 locations of Slice1

The "reference pass" array slice is a reference pass.

Nine, map
Disclaimer: Var persondb map[string] PersonInfo
Persondb = Make (map[string] PersonInfo)

Insert a few data into this map.
persondb["12345"] = personinfo{"12345", "Tom", "Hostel 203,..."}
persondb["1"] = personinfo{"1", "Jack", "101,..."}
From this map look for the key "1234" information
person, OK: = persondb["1234"]
OK is a return bool type and returns true to indicate that the corresponding data was found
If OK {
Fmt. Println (' Found person ', person. Name, "with ID 1234.")
} else {
Fmt. Println ("Did not do not find the person with ID 1234.")
}

Created an initial storage capacity of 100 map:mymap = Make (map[string] PersonInfo, 100)

Assignment: mymap["1234"] = personinfo{"1", "Jack", "101,..."}
Delete: Delete (MyMap, "1234")
Lookup: value, OK: = mymap["1234"]
If OK {//Found
Process the found value
}

A "reference pass" map is a reference pass.

The types of Golang in the "★ ¡ï cited semantic" are: array slicing, map, channel, interface.
struct (Class) objects are often created through new, which is a reference pass, and new is itself a pointer.
A direct declaration of a struct-obtained variable is passed by value. ★★★★★


X. structure struct

Define a new type: type integer int: Defines an integer type that is the same as int.
Type Header map[string][]string

Structure:
Type Rect struct {
X, y float64
width, height float64
}

Func (R *rect) area () float64 {
Return r.width * r.height
}
Instantiating an object:
Rect1: = new (Rect)
Rect2: = &rect{}
RECT3: = &rect{0, 0, 100, 200}
Rect4: = &rect{width:100, height:200}
You can also RECT5: = rect{}.

Add & Symbol and new is a pointer object, no is a value object, this is inconsistent with PHP, Java, when passing the object to decide whether to pass the pointer or value.
Now it's better to use a citation declaration.

Constructor: View the official document, Golang does not have a constructor function to say. If you must do some work when initializing an object, you can encapsulate the method that generated the instance yourself.
Func newpoem (param string, p. interface{}) *poem
Example:
Func Newpoem (author string) (poem *poem) {
poem = &poem{}
Poem. Author = Author
Return
}

A struct is a combination.

"TIPS": traditional inheritance, there are two aspects of the role: the first is reuse, that is, a subclass of the parent class of a part of the method, and then add some special. The second is to say that the parent class provides
A common representation, different subclasses to implement, this is also very common such as abstract class.
Then the first one should be completely switched to the combination of thinking, while the second is achieved through interface. Java has no virtual keyword, and the introduction of Interface,go also preserves
Interface, solves the second problem. The first go is implemented directly through a combination.

11, Interface interface

  Prior to the advent of the Go language, the interface was primarily a contractual existence between different components. The implementation of the contract is mandatory, and you must declare that you did implement the interface.
  In order to implement an interface, you need to inherit from that interface.
 
  In the go language, a class only needs to implement all the functions that the interface requires, and we say that this class implements the interface. Can be assigned to this interface.
 
  "interface assignment": var b lessadder = &a ... (1)   var b lessadder = a ... (2)    should use 1 of the wording, 2 will have a problem.
 
  "interface query":
 var file1 Writer = ...
  if file5, OK: = File1. (both. IStream); OK {
   ....
 }
  This if statement checks if the object instance pointed to by the File1 interface implements both. The IStream interface, if implemented, executes a specific code.
 
  In the Go language, you can ask the interface whether the object it points to is a type, such as:
  var file1 Writer = ...
  if file6, OK: = File1. (*file); OK {
    ....
  }
  This if statement determines whether the object instance pointed to by the File1 interface is a *file type, and if so, executes the specific code.
 
  "type query":
 var v1 interface{} = ...
  switch V: = v1. (type) {
   case int://The type of v now is int
   case string://The type of V now is string
   &NBSP, .....
  }

Interfaces can assign values to interfaces. An interface is a reference pass.

-------------------------------------------
var i itest |
SP: = new (Stest) |
i = SP
Fmt. Println ("point I", unsafe.) Sizeof (i)) |
Fmt. Println ("Point S", unsafe.) Sizeof (sp)) |
I.do () |
SS: = stest{}
i = SS |
Fmt. Println ("struct i", unsafe. Sizeof (i)) |
Fmt. Println ("struct S", unsafe.) Sizeof (ss)) |
Output:
Point I 8 |
Point S 4 |
struct I 8
struct S 40
Visible: The interface type is always 8, regardless of whether it is a new pointer or a struct that is assigned to him. | The pointer size of the struct is 4.
-------------------------------------------
12. Channel:

Disclaimer: Var channame chan ElementType. such as Var ch chan int or, we declare a map, element is bool type Channel:var m map[string] Chan bool

Definition: Defining a channel is also very simple, using the built-in function make () can: ch: = make (chan int)

Creating a buffered channel is actually very easy: c: = make (chan int, 1024)
When you call make (), the buffer size is passed in as the second parameter, such as the above example creates an int type channel of size 1024,
Even if there is no reader, the writer can write to the channel all the time and will not block until the buffer is filled out.

One-way channel:
var ch1 chan Int//CH1 is a normal channel, not one-way
var CH2 chan<-float64//CH2 is a one-way channel for writing float64 data only
var CH3 <-chan INT//CH3 is a one-way channel and is used only to read int data
should be more suitable for use in function parameters.

Close: Close (CH).
X, OK: = <-ch This usage is similar to the process of getting value from a key in map, just look at the second bool return value, and if the return value is False, the CH has been closed.

The "reference Pass" channel is a reference pass.


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.