Closure : a reference function associated therewith and a combined overall environment.
Best Practice : Write a program, specific requirements are as follows:
- Write a function
makeSuffix(suffix string)
that can receive a file extension (for example .jpg), and returns a closure; - 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; strings.HasSuffix
The 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: