Skip to content

doc: change Interface example to use best practices in "Effective Go" #28773

@benhoyt

Description

@benhoyt

Per thread on golang-dev, I have a couple of comments about the code example in the Interfaces section of "Effective Go":

type Sequence []int

// ... Len, Less, and Swap methods ...

// Method for printing - sorts the elements before printing.
func (s Sequence) String() string {
    sort.Sort(s)
    str := "["
    for i, elem := range s {
        if i > 0 {
            str += " "
        }
        str += fmt.Sprint(elem)
    }
    return str + "]"
}

It seems to me there are a couple of things that aren't good habits in this example, and if that's the case, that we shouldn't be showing them as examples in Effective Go:

  1. Having a String() method modify the object (by sorting it in place). There's not actually a strict contract that disallows that, but I would definitely not expect that a String() method would modify the object under my feet. If it it's going to format it sorted, it should make a copy of the slice and sort the copy.

  2. Appending to a string over and over in a loop. I'm not 100% sure how clever the compiler is, but won't this allocate a new string and copy the bytes each time around the loop, leading to O(N^2) behavior? (Quick test showing N^2 behaviour: https://play.golang.org/p/98e9uMsC384) I usually try to avoid appending to a string inside a loop like this for that reason, and instead append() to a slice of strings or write to a bytes buffer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions