Skip to content

strings: document that order of pairs matters in NewReplacer #32699

Description

@pam4

The current documentation doesn't specify the result of the following code (could be either "declare" or "decodel") because they both match at the same starting position:

strings.NewReplacer("decl", "declare", "dec", "decode").Replace("decl")

The actual result is "declare", i.e. the first pair takes precedence (not the longest old string).
I just run into a use case that would require this precedence to be guaranteed, but I can't rely on it because it's not documented.

Looking at the code I presume the precedence is intentional: the generic algorithm uses a lookup trie for prioritized key/value pairs, and keys are added with decreasing priority, see here (len(oldnew)-i is the priority).

Unless there is actually a reason for it to be left undefined, I propose something like:

Leftmost matches take precedence, and among those, the leftmost pair in NewReplacer's arguments takes precedence.

Ok, hopefully someone will come up with better words...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.help wanted

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions