I was writing some Rust code to parse time data, and partway through I noticed the value had an extra ' around it that needed to be stripped. I wrote the comment on line 242 so Copilot would get to work, and it suggested line 243. That’s correct, but the more correct and more sensible solution is the one I wrote on line 244.

For the uninitiated:
- Line 243 says: if there’s a string
'at the start or end of the date string, remove it. - Line 244 says: if there’s a character
'at the start or end of the date string, remove it.
For the initiated:
Both
&strandcharimplement thePattern Traitin Rust, which is why both versions work.
In Copilot’s version, two static strings get allocated in
.data, and for them two fat pointers get built on the function’s stack when line 243 runs. In my version, on the other hand, just two bytes’ worth of numbers get hardcoded, and there’s no extra storage involved.Even though
&strandcharboth implementPattern, their implementations are different.In the
&strimplementation, where you’re effectively comparing two strings, it first checks that the needle isn’t the empty string, and then the lengths of the two strings are compared. Only if the needle is shorter than the haystack does it then check whether the needle’s length is one, in which case only the first byte is examined.In contrast, the
charimplementation skips all of that and checks the first byte directly. In effect, thecharimplementation is two branches faster!Of course, premature optimization is for the short-sighted, and the compiler and the CPU back there will probably put us in our place anyway!
I was wondering why Copilot would suggest something like this in the first place, and two reasons came to mind:
- People are genuinely lazy, and typing
"'"is easier for them than'\''because it’s one character shorter! - Python! I feel like I read somewhere that in Python, using
' 'for strings is frowned upon and people are advised to always use" ". And since GitHub is full of Python code, Copilot basically starts all its string-related suggestions with"instead of'.
- People are genuinely lazy, and typing