Here’s a way to do a similar thing now:
https://play.golang.org/p/CtEYUo6MuqN
func main() {
x := []int{5, 1, 4, 2, 3}
sort.Sort(ClosureSort(func() int { return (len(x)) },
func(i, j int) bool { return x[i] < x[j] },
func(i, j int) { x[i], x[j] = x[j], x[i] }))
fmt.Print(x)
}
The inside func could take a struct instead of multiple arguments to keep
the interface method names. It would be a straightforward package that
could probably be simplified from this playground example.
Matt
On Sunday, April 8, 2018 at 1:35:06 PM UTC-5, Kenneth Duda wrote:
>
> Seven years later, I had the same idea as Js.
>
> Before:
>
> type intslice []int func (x intslice) Len() int { return len(x) } func (x
> intslice) Less(i, j int) bool { return x[i] < x[j] } func (x intslice)
> Swap(i, j int) { x[i], x[j] = x[j], x[i] } func main() { x := intslice{5,
> 1, 4, 2, 3} sort.Sort(x) log.Print(x) }
> After:
> func main() { x := []int{5, 1, 4, 2, 3} sort.Sort(sort.Interface{ Len() {
> return(len(x)) }, Less(i,j int) { return x[i] < x[j] }, Swap(i,j int) {
> x[i], x[j] = x[j], x[i] }, } log.Print(x) }
>
> In my opinion, the latter is more elegant, because I don't have to change
> x's type to get the behavior I want, and because I can place the code that
> satisfies the interface where I use the interface. Like Js indicated, the
> closure in which the interface literal is created would serve as the state
> for the interface literal's implementation.
>
> Thanks,
> -Ken
>
> Kenneth Duda
>
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.