blob: edd1497d9e58811add83d1fd72378912a5396e87 [file] [log] [blame]
Dan Willemsenbc60c3c2021-12-15 01:09:00 -08001// 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
5package strings
6
7import (
8 "unsafe"
9)
10
11// Clone returns a fresh copy of s.
12// It guarantees to make a copy of s into a new allocation,
13// which can be important when retaining only a small substring
14// of a much larger string. Using Clone can help such programs
15// use less memory. Of course, since using Clone makes a copy,
16// overuse of Clone can make programs use more memory.
17// Clone should typically be used only rarely, and only when
18// profiling indicates that it is needed.
19// For strings of length zero the string "" will be returned
20// and no allocation is made.
21func Clone(s string) string {
22 if len(s) == 0 {
23 return ""
24 }
25 b := make([]byte, len(s))
26 copy(b, s)
27 return *(*string)(unsafe.Pointer(&b))
28}