How to get a filename without extension in Go

If you want to grab the name of a file without its extension, you can take a slice of the complete string as shown below:

main.go
func fileNameWithoutExtSliceNotation(fileName string) string {
	return fileName[:len(fileName)-len(filepath.Ext(fileName))]
}

func main() {
	fmt.Println(fileNameWithoutExtSliceNotation("abc.txt")) // abc
}

In this case, the extension length is subtracted from the length of the full string and the result is used to create a substring that excludes the extension.

Another way is to use the strings.TrimSuffix method to remove the trailing suffix string specified in its second argument:

main.go
func fileNameWithoutExtTrimSuffix(fileName string) string {
	return strings.TrimSuffix(fileName, filepath.Ext(fileName))
}

func main() {
	fmt.Println(fileNameWithoutExtTrimSuffix("abc.txt")) // abc
}

This method is a arguably more readable than the previous one, but it’s also slower because TrimSuffix needs to make sure the suffix matches before removal. Here’s a benchmark that shows how the slice notation method is approximately twice as fast as the trim suffix method:

$ go test -bench=.
goos: linux
goarch: amd64
pkg: github.com/ayoisaiah/demo
BenchmarkFileNameWithoutExtSliceNotation-4   	201546076	         5.91 ns/op
BenchmarkFileNameWithoutExtTrimSuffix-4      	100000000	        12.1 ns/op
PASS
ok  	github.com/ayoisaiah/demo	3.017s

Thanks for reading, and happy coding!