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.

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

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解