Weird behaviour of strings.Trim()

Hello gophers, I’m having strange results with this code:

prefix := "/opt/research"
l := []string{
	"/opt/research/comm/aa/bb/file1.xml",
	"/opt/research/comm/cc/dd/file2.xml",
	"/opt/research/non_comm/aa/bb/file1.xml",
	"/opt/research/non_comm/cc/dd/file2.xml",
}

for _, v := range l {
	fmt.Println(strings.TrimLeft(v, prefix))
}

(link to the playbook: https://play.golang.org/p/QhWN-MUk97Q)

I was expecting this:

comm/aa/bb/file1.xml
comm/cc/dd/file2.xml
non_comm/aa/bb/file1.xml
non_comm/cc/dd/file2.xml

but instead I got this:

mm/aa/bb/file1.xml
mm/cc/dd/file2.xml
non_comm/aa/bb/file1.xml
non_comm/cc/dd/file2.xml

The same happens with strings.Trim()

Any ideas of why that happens?

I think TrimPrefix is best choice.

1 Like

strings.TrimLefts second argument is namen cutset, not prefix. So it removes everything from the left that is in the cutset.

This is as documented, also it turns out, the documentation also confirms what @Yamil_Bracho says:

To remove a prefix, use TrimPrefix instead.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.