This repository contains the solutions of the exercises in the book Go Programming Language.
Similar to #gopl-solutions
How to run
1.3 $ go run main.go
1.4 $ go run main.go t1 t2 t3
1.5 & go build ./1.5 > out.gif
1.6 & go build ./1.6 > out.gif
1.7 $ go build ./1.7 http://gopl.io
1.8 $ go build ./1.8 http://gopl.io ./1.8 gopl.io
1.9 $ go build ./1.9 http://gopl.io ./1.9 gopl.io
1.10 $ go build ./1.10 http://gopl.io
1.11 ./1.10 http://Google.Com http://Youtube.Com http://Facebook.Com http://Wikipedia.Org http://Yahoo.Com http://Twitter.Com http://Amazon.Com http://Instagram.Com
1.12 $ go run main.go http://localhost:8000/?cycles=20;res=0.001;size=100;nframes=64;delay=8
2.1
//add
2.2 //using package without compiling: go build main.go ./main -40 //altarnative way without build: go run main.go 30 50
3.1 //using SVG standard for XML line drawings (advanced) go run main.go //result file is in tmp/yourfile folder //insert result here: https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_myfirst
3.2 //same as 3.1 //eggbox folder //moguls folder //saddle folder
3.3 //same as 3.1
3.4 go run main.go http://localhost:8000/?width=1000;height=540;cells=49;fill=black
3.5 go run main.go
3.6 go run main.go
3.7 go run main.go
3.8 go run main.go //21.08s elapsed go run mainC64.go //5.85s elapsed go run mainBigFloat.go //56.61s elapsed go run mainBigRat.go //28.51s elapsed
3.9 go run main.go http://localhost:8000/?xmin=-2;ymin=-2;zoom=1
3.10 $ go run main.go 123456 1234567890
3.11 $ go run main.go -46237123.456 -123.4567890 -12.3 -46237123.456765
3.12 $ go run main.go
3.13 $ go run main.go
4.1 $ go run main.go
4.2
4.3 $go run main.go
4.4 $go run main.go
4.5 $go run main.go
4.6 $go run main.go
4.7 $go run main.go
4.8 $go run main.go
4.9 $go run main.go < main.go
4.10 $go run main.go repo:golang/go is:open json decoder
4.11 $go run main.go create $go run main.go read $go run main.go update $go run main.go delete $go run main.go search repo:golang/go is:open json decoder
4.11 borrowed $go run main.go go run *.go read Julineo golang1training 1 //not working go run *.go create Julineo golang1training 2 go run *.go delete Julieno golang1training 2
4.12 $go run main.go //idx will be created
$go run xkcd.go
4.13 Became a patreon at https://omdbapi.com/ Generay API keys at https://omdbapi.com/apikey.aspx
$go run poster.go [your key here] Batman
4.14 //run webserver $go run main.go repo:golang/go is:open json open browser and navigate to users, issues, milestones http://localhost:8000
5.1 $ go build golang1training/5.1/findlinksr $ ./fetch https://golang.org | ./findlinksr
5.2 $ go build golang1training/5.2/popmap $ ./fetch https://golang.org | ./popmap
5.3 $ go build golang1training/5.3/htmltext $ ./fetch https://golang.org | ./htmltext
5.4 $ go run main.go https://golang.org
5.5 $ go run main.go https://golang.org/doc/
5.6 $ go run main.go //result file is in yourfile //insert result here: https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_myfirst
5.7 $ go run outline.go https://golang.org $ go test
5.8 $ go run getbyid.go topbar https://golang.com https://golang.org/project/
5.9 $ go test
5.10
5.11 //not solved, will get back later
5.12 $ go run outline.go http://www.golang.com
5.13 go run findlinks.go https://www.derekshoemaker.com http://www.alexfast.org http://www.bradfitz.com https://www.calhoun.io
5.15 $ go test
5.16 $ go test
5.17 $ go run main.go
5.18 $ go run main.go https://www.golang.com https://www.golang.com/doc
6.1 $ go run main.go
6.2 $ go run main.go
7.1 $ go run main.go
7.2 $ go run main.go
7.3 $ go test
7.6 $ go run tempflag.go -temp 273.15K
The Go Programming Language Exercises:
chapter.exercise
Index
01.01 Modify the echo program to also print @c(os.Args[0]) 01.02 echo program to print the index and value of each of its arguments, one per line. 01.03 str += VS strings.Join 01.04 dup2 to print the names of all files in which each duplicated line occurs 01.05 Change the Lissajous program’s color palette to green on black 01.06 Modify the Lissajous program to produce images in multiple colors 01.07 Use io.Copy(dst, src) it instead of ioutil.ReadAll to copy the response http.Body to os.Stdout 01.08 Modify fetch to add the prefix "http://" to each argument URL if it is missing. 01.09 Modify fetch to also print the HTTP status code, found in resp.Status. 01.10 Find a web site that produces a large amount of data. Investigate caching by running @c(fetchall) twice in succession to see whether the reported time changes much. Do you get the same content each time? Modify @c(fetchall) to print its output to a file so it can be examined. 01.11 Try fetchall) with longer argument lists, such as samples from the top million web sites available at http://www.alexa.com/. How does the program behave if a web site just doesn’t respond? (Section 8.9 describes mechanisms for coping in such cases.) 01.12 Modify the Lissajous server to read parameter values from the URL. For example, you might arrange it so that a URL like http://localhost:8000/?cycles=20 sets the number of cycles to 20 instead of the default 5. Use the strconv.Atoi function to convert the string parameter into an integer. You can see its documentation with go doc strconv.Atoi. 02.01 Add types, constants, and functions to tempconv for processing temperatures in the Kelvin scale, where zero Kelvin is -273.15°C and a difference of 1K has the same magnitude as 1°C. 02.02 Write a general-purpose unit-conversion program analogous to cf that reads numbers from its command-line arguments or from the standard input if there are no arguments, and converts each number into units like temperature in Celsius and Fahrenheit, length in feet and meters, weight in pounds and kilograms, and the like. 02.03 Rewrite PopCount to use a loop instead of a single expression. Compare the performance of the two versions. (#Section 11.4 shows how to compare the performance of different implementations systematically.) 02.04 Write a version of PopCount that counts bits by shifting its argument through 64 bit positions, testing the rightmost bit each time. Compare its performance to the tablelookup version. 02.05 The expression x&(x-1) clears the rightmost non-zero bit of x. Write a version of PopCount that counts bits by using this fact, and assess its performance. 03.01 If the function f returns a non-finite float64 value, the SVG file will contain invalid elements (although many SVG renderers handle this gracefully). Modify the program to skip invalid polygons. 03.02 Experiment with visualizations of other functions from the math package. Can you produce an egg box, moguls, or a saddle? 03.03 Color each polygon based on its height, so that the peaks are colored red (#ff0000) and the valleys blue (#0000ff). 03.04 Following the approach of the Lissajous example in Section 1.7, construct a web server that computes surfaces and writes SVG data to the client. The server must set the Content-Type header like this: 03.05 Implement a full-color Mandelbrot set using the function image.NewRGBA and the type color.RGBA or color.YCbCr. 03.06 Supersampling is a technique to reduce the effect of pixelation by computing the color value at several points within each pixel and taking the average. The simplest method is to divide each pixel into four subpixels. Implement it. 03.07 Another simple fractal uses Newton’s method to find complex solutions to a function such as z4-1 = 0. Shade each starting point by the number of iterations required to get close to one of the four roots. Color each point by the root it approaches. 03.08 Rendering fractals at high zoom levels demands great arithmetic precision. Implement the same fractal using four different representations of numbers: complex64, complex128, big.Float, and big.Rat. (The latter two types are found in the math/big package. Float uses arbitrary but bounded-precision floating-point; Rat uses unbounded-precision rational numbers.) How do they compare in performance and memory usage? At what zoom levels do rendering artifacts become visible? 03.09 Write a web server that renders fractals and writes the image data to the client. Allow the client to specify the x, y, and zoom values as parameters to the HTTP request. 03.10 Write a non-recursive version of comma, using bytes.Buffer instead of string concatenation. 03.11 Enhance comma so that it deals correctly with floating-point numbers and an optional sign. 03.12 Write a function that reports whether two strings are anagrams of each other, that is, they contain the same letters in a different order. 03.13 Write const declarations for KB, MB, up through YB as compactly as you can. 04.01 Write a function that counts the number of bits that are different in two SHA256 hashes. (See PopCount from Section 2.6.2.) 04.02 Write a program that prints the SHA256 hash of its standard input by default but supports a command-line flag to print the SHA384 or SHA512 hash instead. 04.03 Rewrite reverse to use an array pointer instead of a slice. 04.04 Write a version of rotate that operates in a single pass. 04.05 Write an in-place function to eliminate adjacent duplicates in a []string slice. 04.06 Write an in-place function that squashes each run of adjacent Unicode spaces (see unicode.IsSpace) in a UTF-8-encoded []byte slice into a single ASCII space. 04.07 Modify reverse to reverse the characters of a []byte slice that represents a UTF-8-encoded string, in place. Can you do it without allocating new memory? 04.08 Modify charcount to count letters, digits, and so on in their Unicode categories, using functions like unicode.IsLetter. 04.09 Write a program wordfreq to report the frequency of each word in an input text file. Call input.Split(bufio.ScanWords) before the first call to Scan to break the input into words instead of lines. 04.10 Modify issues to report the results in age categories, say less than a month old, less than a year old, and more than a year old. 04.11 Build a tool that lets users create, read, update, and delete GitHub issues from the command line, invoking their preferred text editor when substantial text input is required. 04.12 The popular web comic xkcd has a JSON interface. For example, a request to https://xkcd.com/571/info.0.json produces a detailed description of comic 571, one of many favorites. Download each URL (once!) and build an offline index. Write a tool xkcd that, using this index, prints the URL and transcript of each comic that matches a search term provided on the command line. 04.13 The JSON-based web service of the Open Movie Database lets you search https://omdbapi.com/ for a movie by name and download its poster image. Write a tool poster that downloads the poster image for the movie named on the command line. 04.14 Create a web server that queries GitHub once and then allows navigation of the list of bug reports, milestones, and users. 05.01 Change the findlinks program to traverse the n.FirstChild linked list using recursive calls to visit instead of a loop. 05.02 Write a function to populate a mapping from element names—p, div, span, and so on—to the number of elements with that name in an HTML document tree. 05.03 Write a function to print the contents of all text nodes in an HTML document tree. Do not descend into <script> or <style> elements, since their contents are not visible in a web browser. 05.04 Extend the visit function so that it extracts other kinds of links from the document, such as images, scripts, and style sheets. 05.05 Implement countWordsAndImages. (See Exercise 4.9 for word-splitting.) 05.06 Modify the corner function in gopl.io/ch3/surface (Section 3.2) to use named results and a bare return statement. 05.07 Develop startElement and endElement into a general HTML pretty-printer. Print comment nodes, text nodes, and the attributes of each element (). Use short forms like instead of when an element has no children. Write a test to ensure that the output can be parsed successfully. (See #Chapter 11.) 05.08 Modify forEachNode so that the pre and post functions return a boolean result indicating whether to continue the traversal. Use it to write a function ElementByID with the following signature that finds the first HTML element with the specified id attribute. The function should stop the traversal as soon as a match is found. 05.09 Write a function expand(s string, f func(string) string) string that replaces each substring $foo within s by the text returned by f("foo"). 05.10 Rewrite topoSort to use maps instead of slices and eliminate the initial sort. Verify that the results, though nondeterministic, are valid topological orderings. 05.11 The instructor of the linear algebra course decides that calculus is now a prerequisite. Extend the topoSort function to report cycles. 05.12 The startElement and endElement functions in gopl.io/ch5/outline2 (Section 5.5) share a global variable, depth. Turn them into anonymous functions that share a variable local to the outline function. 05.13 Modify crawl to make local copies of the pages it finds, creating directories as necessary. Don’t make copies of pages that come from a different domain. For example, if the original page comes from https://golang.org, save all files from there, but exclude ones from https://vimeo.com. 05.14 Use the breadthFirst function to explore a different structure. For example, you could use the course dependencies from the topoSort example (a directed graph), the file system hierarchy on your computer (a tree), or a list of bus or subway routes downloaded from your city government’s web site (an undirected graph). 05.15 Write variadic functions max and min, analogous to sum. What should these functions do when called with no arguments? Write variants that require at least one argument. 05.16 Write a variadic version of strings.Join. 05.17 Write a variadic function ElementsByTagName that, given an HTML node tree and zero or more names, returns all the elements that match one of those names. Here are two example calls: 05.18 Without changing its behavior, rewrite the fetch function to use defer to close the writable file. 05.19 Use panic and recover to write a function that contains no return statement yet returns a non-zero value. 06.01 Implement these additional methods: 06.02 Define a variadic (*IntSet).AddAll(...int) method that allows a list of values to be added, such as s.AddAll(1, 2, 3). 06.03 (*IntSet).UnionWith computes the union of two sets using |, the word-parallel bitwise OR operator. Implement methods for IntersectWith, DifferenceWith, and SymmetricDifference for the corresponding set operations. (The symmetric difference of two sets contains the elements present in one set or the other but not both.) 06.04 Add a method Elems that returns a slice containing the elements of the set, suitable for iterating over with a range loop. 06.05 The type of each word used by IntSet is uint64, but 64-bit arithmetic may be inefficient on a 32-bit platform. Modify the program to use the uint type, which is the most efficient unsigned integer type for the platform. Instead of dividing by 64, define a constant holding the effective size of uint in bits, 32 or 64. You can use the perhaps too-clever expression 32 << (^uint(0) >> 63) for this purpose. 07.01 Using the ideas from ByteCounter, implement counters for words and for lines. You will find bufio.ScanWords useful. 07.02 Write a function CountingWriter with the signature below that, given an io.Writer, returns a new Writer that wraps the original, and a pointer to an int64 variable that at any moment contains the number of bytes written to the new Writer. 07.03 Write a String method for the *tree type in gopl.io/ch4/treesort (Section 4.4) that reveals the sequence of values in the tree. 07.04 The strings.NewReader function returns a value that satisfies the io.Reader interface (and others) by reading from its argument, a string. Implement a simple version of NewReader yourself, and use it to make the HTML parser (Section 5.2) take input from a string. 07.05 The LimitReader function in the io package accepts an io.Reader r and a number of bytes n, and returns another Reader that reads from r but reports an end-of-file condition after n bytes. Implement it. 07.06 Add support for Kelvin temperatures to tempflag. 07.07 Explain why the help message contains °C when the default value of 20.0 does not. 07.08 Many GUIs provide a table widget with a stateful multi-tier sort: the primary sort key is the most recently clicked column head, the secondary sort key is the second-most recently clicked column head, and so on. Define an implementation of sort.Interface for use by such a table. Compare that approach with repeated sorting using sort.Stable. 07.09 Use the html/template package (Section 4.6) to replace printTracks with a function that displays the tracks as an HTML table. Use the solution to the previous exercise to arrange that each click on a column head makes an HTTP request to sort the table. 07.10 The sort.Interface type can be adapted to other uses. Write a function IsPalindrome(s sort.Interface) bool that reports whether the sequence s is a palindrome, in other words, reversing the sequence would not change it. Assume that the elements at indices i and j are equal if !s.Less(i, j) && !s.Less(j, i). 07.11 Add additional handlers so that clients can create, read, update, and delete database entries. For example, a request of the form /update?item=socks&price=6 will update the price of an item in the inventory and report an error if the item does not exist or if the price is invalid. (Warning: this change introduces concurrent variable updates.) 07.12 Change the handler for /list to print its output as an HTML table, not text. You may find the html/template package (Section 4.6) useful. 07.13 Add a String method to Expr to pretty-print the syntax tree. Check that the results, when parsed again, yield an equivalent tree. 07.14 Define a new concrete type that satisfies the Expr interface and provides a new operation such as computing the minimum value of its operands. Since the Parse function does not create instances of this new type, to use it you will need to construct a syntax tree directly (or extend the parser). 07.15 Write a program that reads a single expression from the standard input, prompts the user to provide values for any variables, then evaluates the expression in the resulting environment. Handle all errors gracefully. 07.16 Write a web-based calculator program. 07.17 Extend xmlselect so that elements may be selected not just by name, but by their attributes too, in the manner of CSS, so that, for instance, an element like