Golang Small Program Test (i)

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

1. Manual implementation of Append

Package Mainimport ("FMT") func Append (slice, data []byte) []byte {L: = Len (slice) Total_len: = Len (slice) + len (data) if tot Al_len >= Cap (slice) {Total_len = Total_len * 2newslice: = make ([]byte, Total_len) copy (Newslice, slice) slice = Newslice }for I, K: = Range data {slice[l+i] = K}return Slice}func main () {slice: = []byte{1, 2}data: = []byte{4, 5, 6}sumslice: = Append (slice, data) fmt. Println (Sumslice)}

Looking at this program again, I think the direct iteration of the copy is possible:

Package Mainimport ("FMT") func sliceappend (S1, S2 []byte) []byte{s1_len:=len (S1) s2_len:=len (S2) total_len:=s1_len+s2_ Lens:=make ([]byte, Total_len) for K, V:=range s1{s[k]=v}for K, V:=range S2{s[s1_len+k]=v}return S}func main () {S1:=[]byte {1,2,3}s2:=[]byte{4,5,6}s:=sliceappend (S1, S2) fmt. Println (s)}

2. Communication using the Channel

Package Mainimport "FMT" Func Main () {A: = yes (chan int) b: = make (chan int) c: = make (chan int) go func (A, B, c Chan int) {f Mt. Println ("A Wait") Select {//case b <-1://fmt. Println ("This would never happen") case <-a:fmt. Println ("A knows B exit")}fmt. Println ("A exit") C <-1} (A, B, c) go func (A, b chan int) {FMT. Println ("B Exit") Close (b) a <-1} (A, b) <-cfmt. Println ("C Exit")}

In this example, a waits for the exit of B and uses c to coordinate the operation of main and Goroutine.

3. Closure function of Golang

To modify the return value using closures:

Package Mainimport "FMT" Func main () {x: = 0exec (func () {x + +) fmt. PRINTLN (x)}func exec (callback func ()) {callback ()}

In this example, declare a fun () type parameter, call it with an image, pass it to the Func () type parameter, and then make the call.

Using the channel to pass the closure function:

Package Mainimport "FMT" import "Math/rand" Var C chan func () func main () {c = Make (chan func ()) go Loop () x: = 0y: = Rand. Int ()% 100exec (func () {for i: = 0; i < y; i++ {x + = 1}}) fmt. Println ("x=", X) fmt. Println ("y=", y)}func Loop () {for {select {case callback: = <-c:callback ()}}}func exec (callback func ()) {C <-callb Ack

In the above example, the closure function is used as the parameter of the function, declaring a func () type channel, and passing the closure function through channel, which realizes function synchronization and callback.

4. Golang Generate MD5 value

The MD5 result length of any string generation is fixed, using Golang to generate a MD5 value for a string and then compare it to the MD5 values generated by other languages:

Package Mainimport "FMT" import "crypto/md5" import "encoding/hex" import "bytes" Func main () {h: = MD5. New () H.write ([]byte ("Hello, can you meet?") ") x: = H.sum (nil) y: = make ([]byte, +) hex. Encode (y, x) fmt. Println (String (y)) Z: = []byte ("E2656fa718dbdb73b1c9b56b5ee2bcef") fmt. Println (bytes. Equal (Y, z))}

5. Channel with Buffering

The go language provides two channel types, with buffers and no buffers. The channel without buffer, send and receive is synchronous, must receive the message received by the end of the sender to unblock. The channel with buffer, before the buffer is full, the send and receive is asynchronous, the sending side of the send operation is only guaranteed to put the message into the buffer. the channel can be closed, and the purpose of the closure is to let the receiver know that there will be no more messages coming from the channel, and we may use the closure of a channel to indicate the end of a certain state. when a channel with a buffer is closed, if there is a message in the buffer, the receiver is informed that the channel is not available after all messages have been received.

Package Mainimport "FMT" Import "Runtime" Func main () {runtime. Gomaxprocs (4) Bufferedchannel: = Make (chan int, ten) Wait: = Make (chan int) for i: = 0; I < 10; i++ {bufferedchannel <-i}close (Bufferedchannel) go func () {for {if j, OK: = <-bufferedChannel; OK {fmt. Println (j)} else {break}}wait <-1} () <-wait}

The result is that all values are printed sequentially, and that "send and receive asynchronously before the buffer is full" does not match.

6. Pointer arithmetic for Golang

The go language does not support pointer arithmetic, and all pointers are used in a controlled range, without the C language *void and then randomly converting something like a pointer type. Recently thinking about how go can operate shared memory, shared memory requires that the pointer be transferred to a different type or the pointer is manipulated to retrieve the data. an experiment was made on the unsafe module built into the go language, and it was found that the go language can do pointer operations as well as the "unsafe" module, but it is just a bit more cumbersome than the C method, but the understanding is the same.

Package Mainimport "FMT" import "unsafe" type Data struct {Col1 byteCol2 intCol3 stringCol4 int}func Main () {var v datafmt.p Rintln (unsafe. Sizeof (v)) FMT. PRINTLN ("----") fmt. Println (unsafe. Alignof (v.col1)) fmt. Println (unsafe. Alignof (v.col2)) fmt. Println (unsafe. Alignof (V.COL3)) fmt. Println (unsafe. Alignof (V.COL4)) fmt. PRINTLN ("----") fmt. Println (unsafe. Offsetof (v.col1)) fmt. Println (unsafe. Offsetof (v.col2)) fmt. Println (unsafe. Offsetof (V.COL3)) fmt. Println (unsafe. Offsetof (V.COL4)) fmt. PRINTLN ("----") V.col1 = 98v. Col2 = 77v. Col3 = "1234567890abcdef" V.COL4 = 23fmt. Println (unsafe. Sizeof (v)) FMT. PRINTLN ("----") x: = unsafe. Pointer (&v) fmt. Println (* (*byte) (x)) fmt. Println (* (*int) (unsafe. Pointer (UIntPtr (x) + unsafe. Offsetof (v.col2))) Fmt. Println (* (*string) (unsafe. Pointer (UIntPtr (x) + unsafe. Offsetof (V.COL3))) Fmt. Println (* (*int) (unsafe. Pointer (UIntPtr (x) + unsafe. Offsetof (V.COL4)))}

There are several conversion rules in the unsafe module's documentation, which makes it easy to do pointer operations after understanding it:

    1. A pointer value of any type can is converted to a pointer.
    2. A Pointer can converted to a Pointer the value of any type.
    3. A uintptr can converted to a Pointer.
    4. A Pointer can converted to a uintptr

For the unsafe module, you need to look at it.

7. Golang Close Channel

In some scenarios it is necessary to have multiple goroutine at the same time to exit together, at least a few channel to do this thing? here is an experiment to close the channel, the experiment run two goruntine blocking the message waiting in Channel C, and then close the channel C in the main function, from the experimental results can be seen two goruntine are correctly from the blocked position to continue to run. So the conclusion is that just by closing a public channel, you can get multiple goruntine to exit together.

Package Mainimport "FMT" Func Main () {    a:=make (chan int)    b:=make (chan int)    c:=make (chan int)    go func () {        <-c        FMT. Println ("A")        a<-1    }    go func () {        <-c        fmt. Println ("B")        b<-1      }    Close (c)    <-a    <-b    fmt. Println ("End.")}

8. Implement the Custom Readfull function

Package Mainimport (//"Errors" "FMT" "io") type upstring stringfunc (US upstring) Read (P []byte) (n int, e error) {I, LUs, LP : = 0, Len (US), Len (p) fmt. Println (LUs, LP) for; I < LUs && i < LP; i++ {if us[i] >= ' A ' && us[i] <= ' z ' {p[i] = Us[i] + ' A '-' a '} else {p[i] = Us[i]}}switch I {case Lus:retur N LUs, nilcase lp:return LP, Io. Eofdefault:return I, Io. Eof}}func Main () {us: = upstring ("asdfasdfqwev234vasdswf$%# @SDAFasdf") P: = Make ([]byte,) n, err: = Io. Readfull (US, p) fmt. Printf ("%s\n", p) fmt. PRINTLN (n, err)}

The read buffer is set to twice times the length of the string, and the string is read two times until it is fully read.

9. Golang interface and polymorphism

Package Mainimport ("FMT", "math")//----------interface--------//type shape interface {area () float64//Calculate areas perimeter () float64 Calculate perimeter}//---------rectangle----------//type rect struct {width, height float64}func (r *rect) area () float64 {//areas return R.W Idth * R.height}func (R *rect) perimeter () float64 {//Perimeter return (r.width + r.height)}//-----------round  ----------//t Ype Circle struct {radius float64}func (c *circle) area () float64 {//areas return math. Pi * C.radius * C.RADIUS}FUNC (c *circle) perimeter () float64 {//Perimeter return 2 * Math. Pi * c.radius}//-----------interface use-----------//func interface_test () {r: = rect {width:2.9, height:4.8}c: = Circle {Radiu S:4.3}s: = []shape{&r, &c}//through pointers for _, SH: = range s {fmt. PRINTLN (SH) fmt. Println (Sh.area ()) fmt. Println (Sh.perimeter ())}}func main () {interface_test ()}

Defer, panic example

Package Mainimport ("FMT") func g (i int) {if i>1 {fmt. Println ("panic!") Panic (FMT. Sprintf ("%v%s", I, "panic.")}} Func f () {defer func () {if r: = Recover (); r! = nil {fmt. Println ("Recovered in F", R)}} () for I: = 0; I < 4; i++ {fmt. Println ("Calling G with", I) g (i) fmt. PRINTLN ("returned normally from G.")}} Func main () {f () fmt. PRINTLN ("returned normally from F.")}
It is possible to artificially introduce panic and then use recover in defer to process panic information. From the above program can be seen, panic occurs, the original function stop execution, the use of recover can handle the information generated by the panic, after processing to continue to execute the main () function, the following content.
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.