diff options
author | Rob Pike <r@golang.org> | 2018-11-26 14:51:08 +1100 |
---|---|---|
committer | Rob Pike <r@golang.org> | 2018-11-26 05:08:25 +0000 |
commit | cf2054088099ca90535f2baf6af02bb495a7439c (patch) | |
tree | 891dc2084c868f132ed63b01c66f269055c867cb /doc/progs/eff_sequence.go | |
parent | 048c9164a0c5572df18325e377473e7893dbfb07 (diff) | |
download | go-git-cf2054088099ca90535f2baf6af02bb495a7439c.tar.gz |
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>
Diffstat (limited to 'doc/progs/eff_sequence.go')
-rw-r--r-- | doc/progs/eff_sequence.go | 9 |
1 files changed, 8 insertions, 1 deletions
diff --git a/doc/progs/eff_sequence.go b/doc/progs/eff_sequence.go index 11c885abf8..ab1826b6ee 100644 --- a/doc/progs/eff_sequence.go +++ b/doc/progs/eff_sequence.go @@ -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 += " " } |