package main

import (
	"fmt"
	"strings"
)

// Implement file suffix modification using anonymous functions and closures
func makeSuffix(suffix string) func (string) string{
	return func (fileName string) string{
		// If the file suffix does not end in suffix, add the suffix, otherwise return the original file name
		if! strings.HasSuffix(fileName, suffix) {return fileName + suffix
		}
		return fileName
	}
}

func main(a){

	f := makeSuffix(".jpg")
	fileName1 := "file.jpg"
	fileName2 := "file"
	fmt.Println(f(fileName1))
	fmt.Println(f(fileName2))
}
Copy the code

The execution result

file.jpg
file.jpg
Copy the code

instructions

MakeSuffix returns an anonymous function f and the parameter “.jpg” that is passed in as an external parameter to form a closure that can be used repeatedly after a “.jpg” is passed in.