Go语言中的副作用

有没有人知道如何用Go语言编写带副作用的函数? 我的意思是像C中的
getchar
函数。 谢谢!     
已邀请:
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
    
在C中,副作用用于有效地返回多个值。 在Go中,返回多个值内置于函数规范中:
func f(a int) (int, int) {
    if a > 0 {
        return a, 1
    }
    return 0,0
}
通过返回多个值,您可以通过函数调用影响函数外部的任何内容。     

要回复问题请先登录注册