String slice functions

Being able to manipulate slices of strings is helpful, as we have seen in previous chapters. The Sprig library helps us perform some string slice manipulation actions. In our example, we'll split a string based on the . character.

First, we import the necessary libraries:

package main

import (
"fmt"
"os"
"text/template"

"github.com/Masterminds/sprig"
)

func main() {

Next, we split our templated string using the . delimiter:

    tpl := `{{$v := "Hands.On.High.Performance.In.Go" | splitn "." 5}}{{$v._3}}`

functionMap := sprig.TxtFuncMap()
t := template.Must(template.New("String
Split").Funcs(functionMap).Parse(tpl))

fmt.Print("String Split into Dict (word 3): ")
err := t.Execute(os.Stdout, tpl)
if err != nil {
fmt.Printf("Couldn't create template: %s", err)
return
}

We also have the ability to sort a templated list into alphabetical order using the sortAlpha function, as follows:

    alphaSort := `{{ list "Foo" "Bar" "Baz" | sortAlpha}}` 
s := template.Must(template.New("sortAlpha").
Funcs(functionMap).Parse(alphaSort))
fmt.Print(" Alpha Tuple: ")
alphaErr := s.Execute(os.Stdout, tpl)
if alphaErr != nil {
fmt.Printf("Couldn't create template: %s", err)
return
}

fmt.Print(" String Slice Functions Completed ")
}

These string manipulations can help us organize lists of strings that are included in templated functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.80.3