Let’s Delve into advanced topics like sorting algorithms, templating, and data formats
full lessons here👇:
https://programmerscareer.com/golang-basic-skill/
Generated by AI, there may be errors, for reference only
Topic: 1.1 Advanced Sorting Algorithms in Golang
To become proficient at sorting in Go, we must familiarize ourselves with the sort
package. The sort
package provides primitives for sorting slices or user-defined collections.
There are several ways to sort different types of data, e.g., Ints, Float64s, Strings. Here’s an example of sorting a slice of integers:
1 | package main |
When you run the program, you’ll see the integers sorted in ascending order.
However, if you want to sort a collection of complex types or want to sort by a custom order, you would need to implement the sort.Interface
on your data. The interface requires three methods: Len()
, Less()
, and Swap()
.
That was just a kick-off; we’ll delve deeper as we progress.
Topic: 1.2 Text Templating in Golang
Golang has a powerful text/template
package which allows you to create text templates that are handy for generating customized output formats.
Let’s say we have a Person struct like so:
1 | type Person struct { |
And we create a new person Alice
who is 25
years old:
1 | person := Person{ |
We could define a template to output a person’s information. Here’s a simple example:
1 | const tpl = `{{.Name}} is {{.Age}} years old.` |
When this program is run, it outputs “Alice is 25 years old.” You can also use conditional statements and loops in your templates, which makes them extremely powerful for generating complex text structures!
Topic: 1.3 Advanced Regular Expression Techniques
In Golang, we employ the regexp
package to work with regular expressions. Let’s peruse some practical examples to gain deep insights.
Let’s begin by checking whether a pattern matches a string:
1 | package main |
We can also replace subsets of strings with other values:
1 | fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) // prints: a <fruit> |
Topic: 1.4 Working with JSON in Golang
JSON (JavaScript Object Notation) is probably the most common data exchange format on the internet today. Go’s encoding/json
package provides functionality to work with JSON data.
Let’s start with a simple example of marshalling a map to a JSON data. Marshalling is the process of transforming memory representation to a data format suitable for storage or transmission.
1 | package main |
When you run the program, you get a JSON representation of the colors
map.
Now, let’s go the other way round and unmarshal the JSON:
1 | var colors map[string]string |
When the program is run, it will print the code for the red color, which is “#ff0000”.
Topic: 1.5 Working with XML in Golang
Much like JSON, XML (eXtensible Markup Language) is another common format for data exchange. Think about it as a more formal, stricter version of HTML.
As with JSON, Go has standard library support for XML, via the encoding/xml
package.
Let’s go straight into an example. Suppose we have XML data representing a cafe menu:
1 | <menu> |
Firstly, we need to define the structure of this XML:
1 | type Dish struct { |
Then we can parse this XML:
1 | var menu Menu |
Let’s say we have the following Menu
object:
1 | menu := Menu{ |
And we want to generate an XML representation of this Menu
object. We can use the xml.Marshal()
function. It works very similar to json.Marshal()
:
1 | xmlData, err := xml.Marshal(menu) |
An important thing to note here is that, by default, xml.Marshal()
doesn’t include a header. If you want the <?xml version="1.0" encoding="UTF-8"?>
header, you should use xml.MarshalIndent()
instead:
1 | xmlData, err := xml.MarshalIndent(menu, "", " ") |
Topic: 1.6 Practical Use Cases
It’s fun to learn new things in theory, but it doesn’t truly come to life until you apply it to real-world use cases. Let’s dive into a couple examples using the Golang knowledge you’ve gained.
Practical Use Case 1: Sorting data
Suppose you have a slice of structs representing some people, and you need to sort them in some way, say by age or name. Ordinarily, you would have to write a sorting algorithm yourself, but Golang provides sorting functions in its standard library. Take the sort.Slice
function, for example:
1 | type Person struct { |
Practical Use Case 2: Parsing and Unmarshalling JSON data
Golang provides excellent support for JSON parsing and generation. Consider a use case where you’re building a web server that needs to receive and send JSON data. When you receive a request with a payload, you could parse the payload into a Go struct:
1 | type User struct { |
Topic: 1.7 Review and Assessments
Review
Let’s recap what we covered:
- Advanced Sorting Algorithms in Golang: We explored how Golang implements sorting algorithms and discussed their usage.
- Text Templating in Golang: We learned the concept of text templates and how to output customized text.
- Advanced Regular Expression Techniques: We dove deeper into the practical applications of regular expressions in Golang.
- Working with JSON in Golang: We got hands-on with Golang’s JSON library, parsing, generating, and manipulating JSON data.
- Working with XML in Golang: We designed, parsed, and implemented XML data similarly to how we did with JSON.
- Practical Use Cases: We discussed concrete examples that utilize these advanced Golang concepts.
Assessments
- Sorting Structs Assessment: Given a struct of ‘Songs’ with fields ‘Title’, ‘Artist’ and ‘Duration’, write a Go program that sorts a slice of these songs by their titles, and then by their duration.
- Templating Assessment: Write a Go program that uses text templating to create a personalized greeting.
- Regular Expression Assessment: Write a Go program that uses a regular expression to validate whether a string is a valid phone number.
- JSON Assessment: Write a Go program that takes in a JSON string representing a user with properties ‘Name’, ‘Email’ and ‘Age’, and parse it to a ‘User’ struct.
- XML Assessment: Write a Go program that creates an ‘Employee’ struct, fills it with some data, and then marshals it to XML.
中文文章: https://programmerscareer.com/zh-cn/go-basic-11/
Author: Wesley Wei – Twitter Wesley Wei – Medium
Note: If you choose to repost or use this article, please cite the original source.
Comments