-
functions that return multiple values define those values in parenthesis:
func MyFunc() (n int, s string, xs []int) {}
-
to implement an interface on a struct, the method must be implemented with a
receiver:
type MyStruct struct {}
func (m MyStruct) Write(p byte[]) (n int, err error) {}
-
like sleep
in bash, Go has a time.Sleep
method which accepts a value of
type time.Duration
:
var sleepTime time.Duration = 5 * time.Second
time.Sleep(sleepTime)
-
one can use a struct to encapsulate configurations:
type CustomSleeper struct {
duration time.Duration
sleep func(time.Duration)
}
func (c CustomSleeper) sleep() {
c.sleep(c.duration)
}
func main() {
sleeper := CustomSleeper{duration: 5, sleep: time.Sleep}
}
-
to implement an interface method, one requires a struct on which to implement the
method
-
an interface method can't be defined on an anonymous struct, as interface
methods have to be defined using receivers, while functions on structs are
equivalent to assigning a function to a variable
-
one can either explicitly pass a value by its address to a function, or
initialise the variable with the address:
buffer := bytes.Buffer{}
fmt.Fprint(&buffer, "foo")
bufferAddress = &bytes.Buffer{}
fmt.Fprint(bufferAddress, "foo")
-
a single struct may implement multiple interfaces