
上QQ阅读APP看书,第一时间看更新
How to do it...
- Open the console and create the folder chapter02/recipe03.
- Navigate to the directory.
- 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)
}
- Run the code by executing go run join.go.
- See the output in the Terminal:

- 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
}
- Run the code by executing go run join.go.
- See the output in the Terminal:
