开始-如何在其方法中修改扩展原始类型?

In go, we can extend primitive types such as string or so, and can define its method.

func (s MyStr) Saying() MyStr {
    return s + ", someone said."
}

How can I define methods handling pointer of its self and modify it.

The method below doesn't work:

func (s *MyStr) Repeat() {
    s = s + ", " + s
}

(mismatched types *MyStr and string)

The biggest objection one should have to this code is that strings are immutable. So, as designed, it would take many steps of indirection to get this to work. If MyStr was instead a bytes.Buffer, or something mutable, then it would be a lot easier to get the behaviour you desire.

Before we get to that, however, there's a very easy and obvious bug that needs fixing. To add s and ", ", you can convert the string to a MyStr, like so:

temp := *s + MyStr(", ") + *s 
s = &temp //Still doesn't work

Of course, since strings are immutable, you haven't changed the string that the s used to point to. The s you have changed is just a copy that was created inside the function call; you haven't really achieved anything.

Here is a version that uses the bytes.Buffer package, which IS mutable.

package main

import "fmt"
import "bytes"

// Not aliasing the type, but embedding, 
// so that we can use it as a receiver
type MyStr struct {*bytes.Buffer}

func (s MyStr) Repeat() {
    temp := s.Bytes()
    s.Write(bytes.NewBufferString(", ").Bytes())
    s.Write(temp)
}


func main() {
    a := MyStr{bytes.NewBufferString("a")}
    a.Repeat()
    fmt.Println(a)
}

// Prints 'a, a'