Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure function with a slice as a parameter

Tags:

go

What is the best way to write a pure function in go if I need to pass a (small) slice in parameter? Slice are not passed by value like array. So it's not possible to guarantee that it will not be modified during the execution of the function. Once solution is to copy the slice every time I call the function. It would work in practice, but I would prefer a more safe solution as there is no way to ensure that a copy will ever be made before the function call.

like image 424
user1612346 Avatar asked Apr 17 '26 09:04

user1612346


1 Answers

You are right that since slices are reference values, a truly pure function with a slice argument is not possible.

Depending on your needs, you could use an array. An array has a fixed number of elements and is declared as follows:

var myArray [10]int

Arrays are copied when passed by value.

Another possibility would be to encapsulate the slice in an interface that only allows to read from the slice, not to write to it.

Here's an example:

package main

import "fmt"

// The interface
type ReadOnlyStringSlice interface {
    Get(int) string
}

// An implementation of ReadOnlyStringSlice
type MyReadOnlySlice struct {
    slice []string
}

func (m MyReadOnlySlice) Get(i int) string {
    e := m.slice[i]
    return e
}

// Your "pure" function
func MyPureFunction(r ReadOnlyStringSlice) {
    fmt.Println(r.Get(0))
}

func main() {
    m := MyReadOnlySlice{[]string{"foo", "bar"}}
    MyPureFunction(m)
}
like image 114
thwd Avatar answered Apr 19 '26 23:04

thwd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!