0

有谁知道如何用 Go 语言编写具有副作用的函数?我的意思是像getcharC 中的函数。

谢谢!

4

2 回答 2

3

ReadByte函数修改缓冲区的状态。

package main

import "fmt"

type Buffer struct {
    b []byte
}

func NewBuffer(b []byte) *Buffer {
    return &Buffer{b}
}

func (buf *Buffer) ReadByte() (b byte, eof bool) {
    if len(buf.b) <= 0 {
        return 0, true
    }
    b = buf.b[0]
    buf.b = buf.b[1:]
    return b, false
}

func main() {
    buf := NewBuffer([]byte{1, 2, 3, 4, 5})
    for b, eof := buf.ReadByte(); !eof; b, eof = buf.ReadByte() {
        fmt.Print(b)
    }
    fmt.Println()
}

Output: 12345
于 2011-01-29T09:20:02.710 回答
2

在 C 中,副作用用于有效地返回多个值。

在 Go 中,返回多个值是内置在函数规范中的:

func f(a int) (int, int) {
    if a > 0 {
        return a, 1
    }
    return 0,0
}

通过返回多个值,您可以通过函数调用影响函数之外的任何内容。

于 2011-01-29T08:52:58.420 回答