dongzhuji1042 2014-05-26 12:36
浏览 18
已采纳

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

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)

  • 写回答

1条回答 默认 最新

  • drhwb470572 2015-06-26 05:17
    关注

    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'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大