The study of Golang Standard library

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



1. Memory allocation

New,make (Slice,map,channel) A return pointer, a return type value


---------concurrency
1. Ability to develop parallel programs using channel and Goroutine. What is Goroutine? The specific collectively referred to as threads, processes, co-routines, allocations and releases on heap space, and consumes only a little more than the allocation stack space.


-----------Goroutine
Func Ready (w string, T int) {
Time. Sleep (time. Duration (t) * time. Second)
Fmt. Println (W, "is ready!")
}


Func Main () {
Two threads and the main thread are running concurrently, and if the main thread does not wait, the program exits directly
Go keyword start a goroutine
Go Ready ("one", 1)
Go Ready ("both", 2)
Fmt. Println ("Main goroutine is waiting!")
The main function waits long enough for all the threads to execute,
But there's no way to know how long it should be to wait until all the threads have exited.
At this point, we need some mechanism to communicate with Goroutine channel
Time. Sleep (2 * time. Second)
}


2. Send or receive values through the channel, which can only be a specific type of channel type, create a pipe using make, and define the type of send or accept value Ci:=make (chan int), Cf:=make (Chan interface{})
CI <-1 sends an integer 1 to the pipe CI, <-ci accepts the value and discards it, I:=<-ci Accept integer values and hold to I
---------------
Global variable so that goroutine can access it
var c Chan int


Func Ready (w string, T int) {
Time. Sleep (time. Duration (t) * time. Second)
Fmt. Println (W, "is ready!")
C <-1
}


Func Main () {
c = Make (chan int)//Initialize C
Go Ready ("one", 1)
Go Ready ("both", 2)
Fmt. Println ("Main goroutine is waiting not long!")
Wait until a value is received from the channel and the received value is discarded
But sometimes it's not known how many Goroutine are started, and the data entered on the Select Listener pipeline
<-c
<-c
}


3. Although Goroutine is executed concurrently, it is not run in parallel, that is, only one goroutine can be run at a time, which is achieved by the CPU's temporal-slice rotation mechanism. Use runtime. Gomaxprocs (n) takes advantage of the CPU's number of cores to set the amount of parallel execution.


Check if the pipe is closed
X, OK: = <-c
If ok = = true {
Fmt. PRINTLN (x)
} else {
Fmt. PRINTLN ("channel is Close")
}


--------
Func Main () {
CH: = make (chan int)
Go Shower (CH)
For I: = 0; I < 10; i++ {
CH <-I
}
}


Func shower (ch chan int) {
for {
J: = <-ch//block, wait until the number is received
Fmt. Printf ("%d\n", J)
}
}



2.gobyexample.com


------Range-over-channels
Func Main () {
CH: = Make (Chan string, 2)
CH <-"one"
CH <-"both"
CH <-"three"
Close (CH)


For V: = Range ch {
Fmt. Println ("ch=", V)
}
A: = <-ch
Fmt. Println (a)
}
-----Timers
Func Main () {
Time1: = time. Newtimer (time. Second * 2)
<-time1. C
Fmt. Println ("Time1 expired")
STOP1: = time1. Stop ()
If STOP1 {
Fmt. Println ("Time1 stopped")
}
Time2: = time. Newtimer (time. Second)


Go func () {
<-time2. C
Fmt. Println ("Time2 expired")
}()
STOP2: = time2. Stop ()
If STOP2 {
Fmt. Println ("Time2 stopped")
}
}
------RegExp
Func Main () {
Match, _: = RegExp. Matchstring ("P ([a-z]+)", "Peach")
Fmt. Println (Match)


R, _: = Regexp.compile ("p ([a-z]+) ch")
Fmt. Println (r.matchstring ("Peach"))
Fmt. Println (r.findstring ("Peach Punch"))
Fmt. Println (R.findstringindex ("Peach Punch"))
Fmt. Println (R.findstringsubmatch ("Peach Punch"))
Fmt. Println (R.findstringsubmatchindex ("Peach Puch"))
Fmt. Println (r.findallstring ("Peach Punch Pinch",-1))


R = RegExp. Mustcompile ("P ([a-z]+) ch")
Fmt. Println (R)
In: = []byte ("Hello")
Fmt. Println (in)
}
---------Sha1-hashes
Func Main () {
S: = "ABCDEFG 0123"
H: = SHA1. New ()
H.write ([]byte (s))//h is a hash table of S-string


BS: = h.sum (nil)
Fmt. Println (h)
Fmt. Printf ("%x\n", BS)//%x is the conversion of a hash result to a hex string
}
-----------url-parsing
-----------Command-Line Arguments
Func Main () {
ARGS1: = os. Args
ARGS2: = os. Args[1:]
ARGS3: = os. ARGS[3]
Fmt. Println (ARGS1)
Fmt. Println (ARGS2)
Fmt. Println (ARGS3)
}
----------base64-encoding
Func Main () {
Data: = "abc123!?" &$* () '-=@~ '
SENC: = base64. Stdencoding.encodetostring ([]byte (data))
Fmt. Println (SENC)


Sdec, _: = base64. Stdencoding.decodestring (SENC)
Fmt. Println (String (SDEC))
}
---------Reading-files
Func Main () {
Data, err: = Ioutil. ReadFile ("note/0704/edit.html")
Check (ERR)
Fmt. Println (String (data))


F, err: = OS. Open ("note/0704/edit.html")
Check (ERR)
B1: = Make ([]byte, 5)
N1, Err: = F.read (B1)
Check (ERR)
Fmt. Printf ("%d bytes:%s\n", N1, String (B1))


O2, Err: = F.seek (6, 0)
Check (ERR)
B2: = Make ([]byte, 2)
N2, Err: = F.read (B2)
Check (ERR)
Fmt. Printf ("%d bytes @%d:%s\n", N2, O2, String (B2))


O3, Err: = F.seek (6, 0)
Check (ERR)
B3: = Make ([]byte, 2)
N3, err: = Io. Readatleast (F, B3, 2)
Check (ERR)
Fmt. Printf ("%d bytes @%d:%s\n", N3, O3, String (B3))


R4: = Bufio. Newreader (f)
B4, err: = R4. Peek (5)
Check (ERR)
Fmt. Printf ("5 bytes:%s\n", String (B4))


Defer F.close ()
}


Func Check (e error) {
If E! = Nil {
Panic (e)
}
}


----------Writing-files
Func Main () {
D1: = []byte ("hello\ngo\n")
ERR: = Ioutil. WriteFile ("config_1", D1, 0644)//file automatically created when not present
Check (ERR)


F, err: = OS. Create ("Config_2")
Check (ERR)
Defer F.close ()
D2: = []byte{115, 111, 48, 97, 65}
N2, Err: = F.write (D2)
Check (ERR)
Fmt. Printf ("Write%d bytes\n", N2)


N3, Err: = F.writestring ("writestring\n")//continue to add after the above content
Fmt. Printf ("WriteString%d bytes\n", N3)
F.sync ()


W: = Bufio. Newwriter (f)
N4, err: = W.writestring ("buffered\n")
Fmt. Printf ("Write%d bytes\n", N4)
W.flush ()
}


---------Environment variables
Func Main () {
Os. Setenv ("FOO", "1")
Fmt. Println ("FOO", OS. Getenv ("FOO"))
Fmt. Println ("BAR", OS. Getenv ("BAR"))


For _, E: = Range OS. Environ () {
Pair: = strings. Split (E, "=")
Fmt. Println (Pair[0])
}
}
----------Map Sort
----------exit
Func Main () {
Defer FMT. Println ("defer func")
Os. Exit (3)//os. Exit (0) No print-1
}
---------




1. Format
Functions, calls and definitions of structs
Structs, constructors, definitions of related methods
You must use Api.go to export interfaces to service and applets. There must be two files Main.go service.go
2. Data
For computers, data is a sequence of 1 and 0, and a sequence can be stored in memory, but the data in memory disappears as it shuts down. Long-term storage in the CD or hard disk.
FileSystem file System. Current directory: The parent directory directory is also the file super User root has all the files hard links the number tough link soft link soft link umask
A computer is essentially a tool for processing data, and a document is a logical vehicle for data storage.
The 3.web frame gin also has a corresponding Beego
200 Successes
3: redirect
404 Request Error
5: Server Error


4.
Public is responsible for the browser interface related processing, requests the resources under the Routes folder, carries on the data parsing, then calls the model layer interface to operate the domain layer database.


Session
User name plus password to determine the identity of the user,
The browser allows the Web server to store a piece of data in the browser. When the browser first accesses, the server's response will contain the data that needs the browser request, the browser will save the data to the local, the browser to visit the same page in the request will contain this data, that is, the cookie


5.gin----Readme
GET
The parameters are in the path.
Query URL Parameters
POST:
Processing of the request
Gin. h{} = = = map[string]interface{}
Gin. Default ()---gin. New ()
(c *gin. Context)
C.html ($, "index.html", gin.h{}) C.json (http. statusok,msg) C.xml (200,gin. h{})


6. Interface
The interface type must be assigned to a variable with the appropriate method to make sense var b tester=&mytest{}
P---Package
T---Type
V---variable
F---function


var a interface{}=nil the interface is equal to nil only if the interface stores both the type and the object are nil


Package Main


Import (
"FMT"
)


Type Vter Interface {
VT (A interface{})
}
Type Pter Interface {
PT (A interface{})
}


Type User struct {
Id int
Name string
}


Func (This User) VT (a interface{}) {
Fmt. Printf ("type:%t,value:%v,paragram:%v\n", this. Id, this. Id, a)
}
Func (This *user) pt (A interface{}) {
Fmt. Printf ("name:%v,type:%t\n", this. Name, this. Name)
}


Func Main () {
U: = user{1, "Jack"}
P: = &u


Vter (U). VT ("Hello")//Use of interface
Vter (P). VT ("World")


var s = vter (u)//define S for interface type, not S. User.ID
}










Structure, method, interface


struct substitution class in go for object-oriented programming
Add a method to the type you define T,*t
= = = The structure calculates the area = = = Interface to achieve sort = =


-------------------------------------
Type Rect struct {
X, y float32
}


Func (R *rect) area () float32 {
Return r.x * R.Y
}
Func (R Rect) prim () float32 {
return r.x + r.y
}


Func newrect (x, y float32) *rect {
return &rect{x, y}
}
Func Main () {
r: = Newrect (1.0, 3.5)
R.x can not use Rect.x, to use object instance to go. That is, the corresponding variable (object) of the type
Initial method of struct a:=rect{2,3} rect{} rect{x:3,y:44} &rect{3,3} new (Rect)
Fmt. Println (r.x, R.y, R.area (), R.prim ())
Rect.x = 22
}
-----------------------------------


Type S1 struct {
Id int
Name string
}
Type Interger int


Func (this *s1) Set () *s1 {
This. Id = 3
This. Name = "Pa"
return this
}
Does not necessarily use pointers when receiving, do not need to change the value of the corresponding type
Func (this S1) print () {
Fmt. Println (This)
}
Func (this interger) print () {
Fmt. Printf ("value:%v,type=%t\n", this, this)
}
Func NewS1 (a int, b string) *s1 {//constructor
Return &s1{a, B}
}
Func Main () {
S: = &s1{id:33, Name: "DF"}
Fmt. PRINTLN (s)
Fmt. Println (S.set ())
S2: = NewS1 (1, "they")
S2.print ()
I: = Interger (4)//type is main. Interger is not an int
I.print ()
}


---------------------------


Type Sorter Interface {
Len () int
less (int, int) bool
Swap (int, int)
}
Type X []int
Type Y []string


Func (P X) len () int {
Return Len (P)
}
Func (P X) Less (i, J int) bool {
return p[i] > P[j]
}
Func (P X) Swap (i, J int) {
P[i], p[j] = P[j], p[i]
}
Func Sort (I Sorter) {
For I: = 0; I <= I.len (); i++ {
For J: = i + 1; J < I.len (); J + + {
If I.less (I, j) {
I.swap (i, J)
}
}
}
}


Func Main () {
ARR1: = []int{12, 9, 8, 66, 15}//error, be sure to define your own type
Arr: = x{12, 9, 8, 66, 15}
Fmt. Printf ("arr1=%t,arr=%t\n", arr, arr1)//arr1=main. X,arr=[]int
Fmt. Println (arr)
Sort (arr)
Fmt. Println (arr)
}




Go Pack (Standard library) learning
http://blog.studygolang.com/2012/11/%E5%AD%A6%E4%B9%A0go%E5%8C%85/
(1). Overview--index (see Functions and types, constants)
Take the time package as an example
Some constants are defined
Defines some types of duration, location, etc.
There are three global functions of After,sleep,tick
(2). Types of concerns and their methods
Taking duration as an example
Look at its definition type
Look at the corresponding method.




Time. If l, it means constant constant
Time. Second---1S is a constant defined below the Duration type, the type Duration int64 its own definition of a new type, representing a two-time interval
Time. Duration (v1) indicates that the V1 is loaded to the specified type, not just the function to use parentheses
Multiple-value t1. The Date () in single-value context indicates that there are multiple return values for the function and that the recipient has only one

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.