Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open the console and create the folder chapter02/recipe03.
  2. Navigate to the directory.
  3. Create the join.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const selectBase = "SELECT * FROM user WHERE %s "

var refStringSlice = []string{
" FIRST_NAME = 'Jack' ",
" INSURANCE_NO = 333444555 ",
" EFFECTIVE_FROM = SYSDATE "}

func main() {

sentence := strings.Join(refStringSlice, "AND")
fmt.Printf(selectBase+"\n", sentence)

}
  1. Run the code by executing go run join.go.
  2. See the output in the Terminal:
  1. Create the join_manually.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const selectBase = "SELECT * FROM user WHERE "

var refStringSlice = []string{
" FIRST_NAME = 'Jack' ",
" INSURANCE_NO = 333444555 ",
" EFFECTIVE_FROM = SYSDATE "}

type JoinFunc func(piece string) string

func main() {

jF := func(p string) string {
if strings.Contains(p, "INSURANCE") {
return "OR"
}

return "AND"
}
result := JoinWithFunc(refStringSlice, jF)
fmt.Println(selectBase + result)
}

func JoinWithFunc(refStringSlice []string,
joinFunc JoinFunc) string {
concatenate := refStringSlice[0]
for _, val := range refStringSlice[1:] {
concatenate = concatenate + joinFunc(val) + val
}
return concatenate
}
  1. Run the code by executing go run join.go.
  2. See the output in the Terminal: