Go Basic: Understanding Sorting, Text Templates, Regular Expressions, JSON, XML in Go

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
2
3
4
5
6
7
8
9
10
11
12
package main  

import (
"fmt"
"sort"
)

func main() {
ints:= []int{7, 2, 4, 8, 1}
sort.Ints(ints)
fmt.Println(ints)
}

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
2
3
4
type Person struct {  
Name string
Age int
}

And we create a new person Alice who is 25 years old:

1
2
3
4
person := Person{  
Name: "Alice",
Age: 25,
}

We could define a template to output a person’s information. Here’s a simple example:

1
2
3
4
5
const tpl = `{{.Name}} is {{.Age}} years old.`  

t := template.New("person")
t, _ = t.Parse(tpl)
t.Execute(os.Stdout, person)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main  

import (
"fmt"
"regexp"
)
func main() {
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match) // prints: true

// Taking it further, we can optimize our work by
// compiling an expression and reusing it using `Compile`:
r, _ := regexp.Compile("p([a-z]+)ch")
fmt.Println(r.MatchString("peach")) // prints: true

}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main  

import (
"encoding/json"
"fmt"
)
func main() {
colors := map[string]string{
"red": "#ff0000",
"green": "#00ff00",
"blue": "#0000ff",
}
bytes, err := json.Marshal(colors)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(bytes))
}

When you run the program, you get a JSON representation of the colorsmap.

Now, let’s go the other way round and unmarshal the JSON:

1
2
3
4
5
6
7
var colors map[string]string  

err := json.Unmarshal(bytes, &colors)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Red color code: %s\n", colors["red"])

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/xmlpackage.

Let’s go straight into an example. Suppose we have XML data representing a cafe menu:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<menu>  
<meal>
<name>Breakfast</name>
<dish>
<name>Pancakes</name>
<price>4.5</price>
</dish>
</meal>
<meal>
<name>Lunch</name>
<dish>
<name>Burger</name>
<price>6</price>
</dish>
</meal>
</menu>

Firstly, we need to define the structure of this XML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type Dish struct {  
Name string `xml:"name"`
Price float64 `xml:"price"`
}

type Meal struct {
Name string `xml:"name"`
Dish Dish `xml:"dish"`
}

type Menu struct {
XMLName xml.Name `xml:"menu"`
Meal []Meal `xml:"meal"`
}

Then we can parse this XML:

1
2
var menu Menu  
xml.Unmarshal(xmlData, &menu)

Let’s say we have the following Menu object:

1
2
3
4
5
6
menu := Menu{  
Meal: []Meal{
{"Breakfast", Dish{"Pancakes", 4.5}},
{"Lunch", Dish{"Burger", 6.0}},
},
}

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
2
3
4
5
6
xmlData, err := xml.Marshal(menu)  
if err != nil {
fmt.Println("Error: ", err)
return
}
fmt.Println(string(xmlData))

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
2
3
4
5
6
xmlData, err := xml.MarshalIndent(menu, "", " ")  
if err != nil {
fmt.Println("Error: ", err)
return
}
fmt.Printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n%s", xmlData)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type Person struct {  
Name string
Age int
}

people := []Person{
{"Richard", 60},
{"Arnold", 22},
{"Jessica", 40},
{"Laura", 35},
}
// To sort by age
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
// To sort by name
sort.Slice(people, func(i, j int) bool {
return people[i].Name < people[j].Name
})

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
2
3
4
5
6
7
8
9
10
type User struct {  
Name string `json:"name"`
Age int `json:"age"`
}

func handler(w http.ResponseWriter, r *http.Request) {
var user User
json.NewDecoder(r.Body).Decode(&user)
// Now you can use user.Name and user.Age
}

Topic: 1.7 Review and Assessments

Review

Let’s recap what we covered:

  1. Advanced Sorting Algorithms in Golang: We explored how Golang implements sorting algorithms and discussed their usage.
  2. Text Templating in Golang: We learned the concept of text templates and how to output customized text.
  3. Advanced Regular Expression Techniques: We dove deeper into the practical applications of regular expressions in Golang.
  4. Working with JSON in Golang: We got hands-on with Golang’s JSON library, parsing, generating, and manipulating JSON data.
  5. Working with XML in Golang: We designed, parsed, and implemented XML data similarly to how we did with JSON.
  6. Practical Use Cases: We discussed concrete examples that utilize these advanced Golang concepts.

Assessments

  1. 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.
  2. Templating Assessment: Write a Go program that uses text templating to create a personalized greeting.
  3. Regular Expression Assessment: Write a Go program that uses a regular expression to validate whether a string is a valid phone number.
  4. 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.
  5. 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.

Go Basic: Understanding Time, Epoch, Time Formatting Parsing, Random Numbers, Number Parsing, URL Parsing, sha256 Hashes, base64 Encoding in Go Go Basic: Understanding File Paths, Directories, Temporary Files and Directories, Embed Directive in Go

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×