Using copy with strings

Posted on Aug 18, 2024

The Go copy built-in copies things from a source slice to a destination slice.

func copy(dst, src []Type) int

It is not using generics, but Type here serves the same purpose. Or does it?

Not exactly! string is a little-known exception:

As a special case, [copy] also will copy bytes from a string to a slice of bytes.

Next time you need to work with strings while reusing a work buffer, copy might just be the perfect candidate to avoid ugly for rune loops.

All fields requesting personally identifiable information (PII) are optional. Any personal data you provide will be kept private and is used solely for moderation purposes. Your information is stored securely on a server in Switzerland and will not be used directly, shared, or disclosed to third parties. By submitting your personal data, you consent to its indefinite storage under these terms. Should you wish to have your data removed or have any privacy concerns, please contact me using the information provided in the 'About' section.