代码之家  ›  专栏  ›  技术社区  ›  meh

为什么指针指向Go字节。缓冲区将其传递给另一个函数时是否需要?

  •  -1
  • meh  · 技术社区  · 6 年前

    在下面的代码中, write_commas

    另一种选择(即不使用指针)会导致空白输出。

    为什么要通过 bytes.Buffer 字节。缓冲区 创建一个副本,这样,字节就被写入一个缓冲区,而没有任何东西在读取?

    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 回复  |  直到 6 年前
        1
  •  2
  •   Adrian    6 年前

    每当您将参数传递给函数时,它都会在该函数中创建一个本地副本。传递指针时,函数将接收指针的副本,该副本指向相同的基础值。因此,如果传递一个指针,函数会影响它所指向的值,调用者会看到这个值。如果改为传递值的副本(而不是传递指针),则函数正在操作副本,这对调用方自己的副本没有影响。