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:
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:
This method is a arguably more readable than the previous one, but it’s also
TrimSuffix needs to make sure the suffix matches before
removal. Here’s a
that shows how the slice notation method is approximately twice as fast as the trim suffix
$ 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!