A few simple examples of Go language test sledgehammer---

Source: Internet
Author: User

Organize the information, find the previous handwritten go language material, now paste it over.

First: Use of channel, create a random number

Package main import "FMT" Import  "Runtime" Func rand_generator_2 () chan int{out: = make (chan int) go func () {for{out< -rand. Int ()}} () return Out}func main () {rand_service_handler: = rand_generator_2 () fmt. Printf ("%d\n", <-rand_service_handler)}

Second: Implementing an example of summing through channel channels

Package MainType Nodeinterface Interface {receive (i int) run () int}type Node struct {name string in_degree int In_c H Chan int out_ch chan int inode nodeinterface}func NewNode (name string, Inode nodeinterface) *node {//Create a Node with two CH Annel return &node{name, 0, make (chan int), make (Chan int.), Inode}}func (from *node) ConnectTo (to *node) {to.in_deg ree++ go func () {i: = <-from.out_ch to.in_ch <-i} ()}func (n *node) Run () {go func () {defer func () {if x: = Recover (); X! = nil {println (n.name, "Panic with value", X) Panic (x)} println (n.    Name, "finished"); } () for N.in_degree > 0 {received: = <-n.in_ch n.inode.receive (Received) n.in_degree--} r ET: = N.inode.run () n.out_ch <-ret} ()}type doublenode struct {Data int}//creates a new Nodefunc Newdoublenode (name Stri ng, data int) *node {return NewNode (name, &doublenode{data})}func (n *doublenode) receive (i int) {}func (n *doubleno De) run () int {return n.data * 2}type sumnode struct {data int}func Newsumnode (name string) *node {return NewNode (name , &sumnode{0})}func (n *sumnode) receive (i int) {n.data + = I}func (n *sumnode) run () int {return N.data}func main ( {sum: = Newsumnode ("sum") sum. Run () for _, num: = range [5]int{1, 2, 3, 5, 6} {node: = Newdoublenode ("double", num) node. ConnectTo (sum) node. Run ()} println (<-sum.out_ch)}

  Third Example: concurrent operation of the go language, the Go language can be adapted to the CPU of the machine to achieve maximum concurrency

Package Mainimport ("FMT" "runtime") var workers = runtime. NUMCPU () type Result struct {jobname stringresultcode intresultinfo string}type Job struct {jobname stringresults chan&l t;-Result}func Main () {///GO language has this line of code at the beginning of most concurrent programs, but this line of code will eventually be superfluous,//Because the Go language runtime system becomes smart enough to automatically fit the machine runtime it runs. Gomaxprocs (runtime. NUMCPU ())//Returns the current number of processors in FMT. Println (runtime. Gomaxprocs (0))//Returns the number of logical processors or cores of the current machine FMT. Println (runtime. NUMCPU ())//simulation of 8 tasks Jobnames: = []string{"Gerry", "WCDJ", "Golang", "C + +", "Lua", "Perl", "Python", "C"}dorequest ( Jobnames)}func dorequest (jobnames []string) {//define required channels tiles jobs: = Make (chan Job, workers) Results: = Make (chan Result , Len (jobnames)) Done: = Make (chan struct{}, workers)//---------------------------------------------/* * The following is a classic framework for Go coprocessor concurrency processing *///to add tasks that require concurrent processing to Jobs ' channel go addjobs (Jobs, jobnames, results)//executes in its own goroutine//root According to the number of CPUs to start the corresponding number of goroutines from jobs scramble for the task to process for I: = 0; I < workers; i++ {Go dojobs (done, jobs)//per executes in its own goroutine}//newCreates a routine that accepts results, waits for all worker routiines to complete the result, and notifies the main Routinego awaitcompletion (done, results)// In the main routine output results processresults (results)//---------------------------------------------}func addjobs (Jobs chan<- Job, Jobnames []string, Results chan<-Result) {for _, JobName: = Range Jobnames {//Add task in channel jobs <-Job{jobnam  E, Results}}close (jobs)}func dojobs (done chan<-struct{}, Jobs <-chan job) {//Remove task in channel and calculate for job: = Range jobs {/* * Defines the type's own method to handle business logic, implementing framework and business separation */job. Do ()}//the end flag for all tasks, an empty struct slice done <-struct{}{}}//method is a class of special function func (Job Job) do () that acts on the value of a custom type. {//Prints the currently processed task name FMT. Printf ("... doing work in [%s]\n", job.jobname)//Simulation results if Job.jobname = = "Golang" {job.results <-result{job.jobname,  0, "OK"}} else {job.results <-result{job.jobname,-1, "Error"}}}func awaitcompletion (Done <-chan struct{}, results Chan Result) {for i: = 0; i < workers; i++ {<-done}close (results)}func processresults (Results <-chan Result) {fo R Result: = Range Results {Fmt. Printf ("Done:%s,%d,%s\n", Result.jobname, Result.resultcode, Result.resultinfo)}}

  Fourth: Network programming, based on go implementation ping operation, more difficult, not yet read

Copyright: The Go Authors. All rights reserved.//Use of this source code are governed by a bsd-style//license so can be found in the license file. Taken from http://golang.org/src/pkg/net/ipraw_test.gopackage pingimport ("bytes" "Errors" "NET" "OS" "Time") const (     Icmpv4echorequest = 8icmpv4echoreply = 0icmpv6echorequest = 128icmpv6echoreply = 129) type icmpmessage struct {type int//TypeCode int//codechecksum int//Checksumbody icmpmessagebody//Bo Dy}type Icmpmessagebody Interface {Len () Intmarshal () ([]byte, error)}//Marshal returns the binary enconding of the ICMP  Echo Request or//reply message M.func (M *icmpmessage) Marshal ([]byte, error) {b: = []byte{byte (M.type), Byte (M.code), 0, 0}if m.body! = nil && M.body.len ()! = 0 {MB, err: = M.body.marshal () if err! = Nil {return nil, err}b = append ( b, mb ...)} Switch M.type {case icmpv6echorequest, Icmpv6echoreply:return B, NIL}CSUMCV: = Len (b)-1//checksum CoveraGES: = UInt32 (0) for I: = 0; i < CSUMCV; i + = 2 {s + = UInt32 (b[i+1]) <<8 | UInt32 (B[i])}if csumcv&1 = 0 {s + = UInt32 (B[CSUMCV])}s = s>>16 + s&0 Xffffs = s + s>>16//place checksum back in header; Using ^= avoids the//assumption the checksum bytes is zero.b[2] ^= byte (^s & 0xFF) b[3] ^= byte (^s >> 8) return B, nil}//Parseicmpmessage parses B as an ICMP message.func parseicmpmessage (b []byte) (*icmpmessage, error) {msglen: = Le N (b) if Msglen < 4 {return nil, errors. New ("message Too Short")}m: = &icmpmessage{type:int (B[0]), Code:int (B[1]), Checksum:int (b[2]) <<8 | int (b[3]) }if Msglen > 4 {var err errorswitch m.type {case icmpv4echorequest, icmpv4echoreply, Icmpv6echorequest, icmpv6EchoReply : m.body, err = Parseicmpecho (b[4:]) if err! = Nil {return nil, Err}}}return m, nil}//Imcpecho represenets an ICMP echo req Uest or reply message body.type icmpecho struct {ID int//IDENTIFIERSEQ int//sequence numberdata []byte//Dat A}funC (P *icmpecho) Len () int {if p = = Nil {return 0}return 4 + Len (p.data)}//Marshal returns the binary enconding of the ICM P echo Request or//reply message body P.func (P *icmpecho) Marshal ([]byte, error) {b: = make ([]byte, 4+len (p.data)) b[0 ], b[1] = byte (p.id>>8), Byte (P.id&0xff) b[2], b[3] = byte (p.seq>>8), byte (p.seq&0xff) Copy (b[4:], p. Data) return B, nil}//Parseicmpecho parses B as an ICMP echo request or reply message Body.func Parseicmpecho (b []byte) (* Icmpecho, error) {bodylen: = Len (b) P: = &icmpecho{id:int (b[0]) <<8 | int (b[1]), Seq:int (b[2]) <<8 | int (b[  3])}if Bodylen > 4 {p.data = make ([]byte, bodylen-4) copy (P.data, b[4:])}return p, Nil}func Ping (address string, timeout int) (alive bool) {err: = Pinger (address, timeout) alive = Err = = Nilreturn}func Pinger (address string, timeout int) (err Error) {//dialing C, err: = Net. Dial ("ip4:icmp", address) if err! = Nil {return}//?c.setdeadline (time. Now (). ADD (time. Duration (Timeout) * time. Second)) deferC.close ()//>>typ: = Icmpv4echorequestxid, Xseq: = OS. Getpid () &0xffff, 1WB, err: = (&icmpmessage{type:typ, code:0,body: &icmpecho{id:xid, SEQ:XSEQ,DATA:BYTES.R Epeat ([]byte ("Go Go Gadget Ping!!!"), 3),},}). Marshal () if err! = Nil {Return}if _, err = C.write (WB); Err! = Nil {Return}var m *icmpmessagerb: = Make ([]byte, 20+len (WB)) for {if _, err = C.read (RB); Err! = Nil {RETURN}RB = IP V4payload (RB) if m, err = Parseicmpmessage (RB); Err! = Nil {return}switch M.type {case icmpv4echorequest, Icmpv6echorequest:continue}break}return}func ipv4Payload (b [] BYTE) []byte {if Len (b) < {return B}hdrlen: = Int (b[0]&0x0f) << 2return B[hdrlen:]}

A few simple examples of Go language test sledgehammer---

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.