You should use the ==
operator to compare strings. It compares the content of the string
values.
What you print is the address of a
and b
variables. Since they are 2 distinct non-zero size variables, their addresses cannot be the same by definition. The values they hold of course may or may not be the same. The ==
operator compares the values the variables hold, not the addresses of the variables.
Your solution with the loop might even result in a runtime panic, if the b
string is shorter than a
, as you index it with values that are valid for a
.
The built-in ==
operator will likely always outperform any loop, as that is implemented in architecture specific assembly code. It is implemented in the runtime
package, unexported function memequal()
.
Also note that the built-in comparison might even omit checking the actual contents of the texts if their string header points to the same data (and have equal length). There is no reason not to use ==
.
The only reason where a custom equal function for string
values would make sense is where the heuristics of your strings are known. E.g. if you know all the string values have the same prefix and they may only differ in their last character. In this case you could write a comparator function which only compares the last character of the strings to decide if they are equal (and only, optionally revert to actually compare the rest). This solution would of course not use a loop.