AHS
AHS

Reputation: 784

Side Effects in Go Language

Does anyone know how to write a function with side effects in the Go language? I mean like the getchar function in C.

Thanks!

Upvotes: 0

Views: 1009

Answers (2)

peterSO
peterSO

Reputation: 166704

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

Upvotes: 3

Olhovsky
Olhovsky

Reputation: 5559

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.

Upvotes: 2

Related Questions