Had to think long and hard about that title ?... now that we've gotten that out of the way, let's write some darn code :)
Pumps brake ? screechhhhh.... Let's do a bit of introduction into what we will be attempting to build today. Incase the title wasn't obvious, we will be building a CLI application that calculates your typing speed in golang - although you can literally build the same application, following the same techniques in any programming language of your choice.
Now, let's code ?
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strings" "time" ) var sentences = []string{ "There are 60 minutes in an hour, 24 hours in a day and 7 days in a week", "Nelson Mandela is one of the most renowned freedom fighters Africa has ever produced", "Nigeria is the most populous black nation in the world", "Peter Jackson's Lord of the rings is the greatest film of all time", }
In our main.go file, we import the packages we will need to write our logic. We also create a slice of sentences. Feel free to add a bunch more.
// A generic helper function that randomly selects an item from a slice func Choice[T any](ts []T) T { return ts[rand.Intn(len(ts))] } // Prompts and collects user input from the terminal func Input(prompt string) (string, error) { fmt.Print(prompt) r := bufio.NewReader(os.Stdin) line, err := r.ReadString('\n') if err != nil { return "", err } return strings.Trim(line, "\n\r\t"), nil } // Compares two strings and keeps track of the characters // that match and those that don't func CompareChars(target, source string) (int, int) { var valid, invalid int // typed some of the words // resize target to length of source if len(target) > len(source) { diff := len(target) - len(source) invalid += diff target = target[:len(source)] } // typed more words than required // resize source to length of target if len(target) <p>We then go on to create a couple of function that will come in handy when we write our application logic.<br> </p> <pre class="brush:php;toolbar:false">func main() { fmt.Println("Welcome to Go-Speed") fmt.Println("-------------------") for { fmt.Printf("\nWould you like to continue? (y/N)\n\n") choice, err := Input(">> ") if err != nil { log.Fatalf("could not read value: %v", err) } if choice == "y" { fmt.Println("Starting Game...") timer := time.NewTimer(time.Second) fmt.Print("\nBEGIN TYPING NOW!!!\n\n") _ = > ") if err != nil { log.Fatalf("could not read value: %v", err) } elasped := timeElapsed(start, time.Now()) valid, invalid := CompareChars(sentence, response) fmt.Print("\nResult!\n") fmt.Println("-------") fmt.Printf("Correct Characters: %d\nIncorrect Characters: %d\n", valid, invalid) fmt.Printf("Accuracy: %d%%\n", accuracy(valid, len(sentence))) fmt.Printf("Precision: %d%%\n", precision(valid, invalid)) fmt.Printf("Speed: %.1fwpm\n", Speed(len(sentence), elasped)) fmt.Printf("Time Elasped: %.2fsec\n", elasped) } if choice == "N" { fmt.Println("Quiting Game...") break } if choice != "N" && choice != "y" { fmt.Println("Invalid Option") } } }
In our main function, we write a welcome message to the terminal and create an infinite loop to run our program. We then print a confirmation message to stdout - terminal - with an option to quit the program. If you choose to continue, a sentence is selected from the slice of sentences previously written and displayed in the terminal just after the start time is recorded. We collect the user input and calculate the time, speed, precision and accuracy then display the results back to the terminal. The infinite loop resets and the application runs again until you opt out of the program.
Voila!!! We just wrote our first program in golang.
The above is the detailed content of Writing a Typing Speed Test CLI Application in Golang. For more information, please follow other related articles on the PHP Chinese website!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
