Go言語で副作用のある関数を書く方法を知っている人はいますか? getchar
私はCの関数のように意味します。
ありがとう!
この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
}
複数の値を返すことにより、関数呼び出しの結果として、関数の外部で好きなものに影響を与えることができます。