dr200166 2018-08-31 15:53
浏览 97
已采纳

传递给另一个函数时,为什么需要指向Go bytes.Buffer的指针?

In the code below, write_commas requires the buffer parameter to be a pointer. It works.

The alternative (ie. NOT using a pointer) results in blank output.

Why is it that passing the actual bytes.Buffer fails to print anything? Or put another way, does passing the actual bytes.Buffer create a copy and thus, the bytes get written to a buffer that nothing is reading?

package main

import (
    "fmt"
    "bytes"
)

func main() {
    s := "1234567898"
    fmt.Println(Comma(s))

}

func Comma(s string) string {
    var buf bytes.Buffer  // <-- bytes.Buffer declared here.
    sbytes := []byte(s)
    decimal := bytes.LastIndex(sbytes,[]byte("."))
    if decimal > 0 {
        whole_part := sbytes[:decimal]
        write_commas(whole_part, &buf)  // <-- Address

        float_part := sbytes[decimal:len(sbytes)]
        for i := len(float_part); i > 0; i-- {
            buf.WriteByte(float_part[len(float_part)-i])
        }
    } else {.
        write_commas(sbytes, &buf)  // <-- Address
    }

    return buf.String()
}

func write_commas(byr []byte, buf *bytes.Buffer) { // <-- Why *bytes.Buffer?
    for i := len(byr); i > 0; i-- {
        buf.WriteByte(byte(byr[len(byr)-i]))
        if i > 1 && (i-1) % 3 == 0 {
            buf.WriteByte(',')
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dsiv4041 2018-08-31 15:56
    关注

    Any time you pass an argument to a function, it creates a local copy within that function. When you pass a pointer, the function receives a copy of the pointer, which points to the same underlying value. So, if you pass a pointer, the function can affect the value it points to, which the caller will then see. If you pass a copy of the value instead (instead of passing a pointer), the function is manipulating the copy, which has no effect on the caller's own copy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?