英文:
Side Effects in Go Language
问题
有人知道如何在Go语言中编写具有副作用的函数吗?
我的意思是像C语言中的getchar函数那样。
谢谢!
英文:
Does anyone know how to write a function with side effects in the Go language?
I mean like the getchar function in C.
Thanks!
答案1
得分: 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()
}
输出:12345
英文:
The ReadByte function modifies the state of the buffer.
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
答案2
得分: 2
在C语言中,副作用被用于有效地返回多个值。
在Go语言中,返回多个值已经内置在函数的规范中:
func f(a int) (int, int) {
    if a > 0 {
        return a, 1
    }
    return 0,0
}
通过返回多个值,你可以在函数调用的结果中影响任何你喜欢的东西。
英文:
In C, side effects are used to effectively return multiple values.
In Go, returning multiple values is built into the specification of functions:
func f(a int) (int, int) {
    if a > 0 {
        return a, 1
    }
    return 0,0
}
By returning multiple values, you can influence anything you like outside of the function, as a result of the function call.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论