Commit cf205408 authored by Rob Pike's avatar Rob Pike

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/151217Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
parent 048c9164
...@@ -2106,12 +2106,14 @@ In this contrived example <code>Sequence</code> satisfies both. ...@@ -2106,12 +2106,14 @@ In this contrived example <code>Sequence</code> satisfies both.
<p> <p>
The <code>String</code> method of <code>Sequence</code> is recreating the The <code>String</code> method of <code>Sequence</code> is recreating the
work that <code>Sprint</code> already does for slices. We can share the work that <code>Sprint</code> already does for slices.
effort if we convert the <code>Sequence</code> to a plain (It also has complexity O(N²), which is poor.) We can share the
effort (and also speed it up) if we convert the <code>Sequence</code> to a plain
<code>[]int</code> before calling <code>Sprint</code>. <code>[]int</code> before calling <code>Sprint</code>.
</p> </p>
<pre> <pre>
func (s Sequence) String() string { func (s Sequence) String() string {
s = s.Copy()
sort.Sort(s) sort.Sort(s)
return fmt.Sprint([]int(s)) return fmt.Sprint([]int(s))
} }
...@@ -2138,6 +2140,7 @@ type Sequence []int ...@@ -2138,6 +2140,7 @@ type Sequence []int
// Method for printing - sorts the elements before printing // Method for printing - sorts the elements before printing
func (s Sequence) String() string { func (s Sequence) String() string {
s = s.Copy()
sort.IntSlice(s).Sort() sort.IntSlice(s).Sort()
return fmt.Sprint([]int(s)) return fmt.Sprint([]int(s))
} }
......
...@@ -28,11 +28,18 @@ func (s Sequence) Swap(i, j int) { ...@@ -28,11 +28,18 @@ func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i] 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. // Method for printing - sorts the elements before printing.
func (s Sequence) String() string { func (s Sequence) String() string {
s = s.Copy() // Make a copy; don't overwrite argument.
sort.Sort(s) sort.Sort(s)
str := "[" str := "["
for i, elem := range s { for i, elem := range s { // Loop is O(N²); will fix that in next example.
if i > 0 { if i > 0 {
str += " " str += " "
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment