0

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

Thanks!

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
AHS
  • 774
  • 1
  • 10
  • 17
  • 3
    I think you'll need to be more specific about what you're after. Go isn't a functional language. There's nothing stopping you from writing functions with side effects. Lots of the functions in packages os, fmt, and net have side effects, for example. – Evan Shaw Jan 29 '11 at 21:32

2 Answers2

3

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
peterSO
  • 158,998
  • 31
  • 281
  • 276
2

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.

Olhovsky
  • 5,466
  • 3
  • 36
  • 47