Go strings.HasSuffix
Check the end of a filename when listing receipts saved as PDFs.
A simple example
strings.HasSuffix
- Start with "abc" and "bc"
- Do this Compare the ending
- Result Yes
package main
import (
"fmt"
"strings"
)
func main() {
value := "abc"
other := "bc"
if strings.HasSuffix(value, other) {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
yes
Syntax
strings.HasSuffix(label, ".pdf")
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goFind filenames with a receipt extension
A document picker displays receipt files alongside unrelated attachments. Filter by the expected ending so the clerk sees the right filenames before opening any of the files.
package main
import (
"fmt"
"strings"
)
func main() {
label := "receipt.pdf"
if strings.HasSuffix(label, ".pdf") {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
yes
The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.
Find a class roster
A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.
package main
import (
"fmt"
"strings"
)
func main() {
value := "class.csv"
other := ".csv"
if strings.HasSuffix(value, other) {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
yes
The final characters match the requested extension.
Exclude a backup export
A registry keeps an earlier export by adding an extra extension to its filename. Test the filename's final suffix before treating the file as part of today's import.
package main
import (
"fmt"
"strings"
)
func main() {
value := "class.csv.old"
other := ".csv"
if strings.HasSuffix(value, other) {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
no
The final extension is .old.
What to watch for
A filename suffix describes a naming convention. It cannot verify the contents of a file.