clone.go 877 B

12345678910111213141516171819202122232425262728
  1. // Copyright 2021 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package strings
  5. import (
  6. "unsafe"
  7. )
  8. // Clone returns a fresh copy of s.
  9. // It guarantees to make a copy of s into a new allocation,
  10. // which can be important when retaining only a small substring
  11. // of a much larger string. Using Clone can help such programs
  12. // use less memory. Of course, since using Clone makes a copy,
  13. // overuse of Clone can make programs use more memory.
  14. // Clone should typically be used only rarely, and only when
  15. // profiling indicates that it is needed.
  16. // For strings of length zero the string "" will be returned
  17. // and no allocation is made.
  18. func Clone(s string) string {
  19. if len(s) == 0 {
  20. return ""
  21. }
  22. b := make([]byte, len(s))
  23. copy(b, s)
  24. return *(*string)(unsafe.Pointer(&b))
  25. }