mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
doc: improve the interface example in Effective Go
The String method is n-squared and overwrites its receiver. Fix both issues, with only a slight loss of clarity. Fixes #28773 Change-Id: I588f69d4cbd72931b28b984671512834473bd466 Reviewed-on: https://go-review.googlesource.com/c/151217 Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
parent
048c9164a0
commit
cf20540880
2 changed files with 13 additions and 3 deletions
|
|
@ -28,11 +28,18 @@ func (s Sequence) Swap(i, j int) {
|
|||
s[i], s[j] = s[j], s[i]
|
||||
}
|
||||
|
||||
// Copy returns a copy of the Sequence.
|
||||
func (s Sequence) Copy() Sequence {
|
||||
copy := make(Sequence, 0, len(s))
|
||||
return append(copy, s...)
|
||||
}
|
||||
|
||||
// Method for printing - sorts the elements before printing.
|
||||
func (s Sequence) String() string {
|
||||
s = s.Copy() // Make a copy; don't overwrite argument.
|
||||
sort.Sort(s)
|
||||
str := "["
|
||||
for i, elem := range s {
|
||||
for i, elem := range s { // Loop is O(N²); will fix that in next example.
|
||||
if i > 0 {
|
||||
str += " "
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue