Best Practices in Go closures (Golang classic case of programming)

Closure : a reference function associated therewith and a combined overall environment.

Best Practice : Write a program, specific requirements are as follows:

  1. Write a function makeSuffix(suffix string)that can receive a file extension (for example .jpg), and returns a closure;
  2. Call closure, you can pass a filename, if the file name is not specified suffix (such as .jpg), then return 文件名.jpg, if there .jpg suffix, the source file name is returned;
  3. strings.HasSuffixThe function may determine whether there is a character string specified suffix.

code show as below:

package main

import (
	"fmt"
	"strings"
)
func makesuffix(suffix string) func(string) string {
	return func(name string) string {
		//如果name没有指定的后缀,则加上,否则就返回原来的名字
		if !strings.HasSuffix(name, suffix) {
			return name + suffix
		}
		return name
	}
}

func main() {
	f2 :=makesuffix(".jpg")
	fmt.Println("文件名处理后=", f2("winter"))
	fmt.Println("文件名处理后=", f2("bird.jpg"))
}

Execution results as shown below:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/93645557