Trying to understand closures - go

Sorry, still a newb in Go. I am trying to write a closure:
https://play.golang.org/p/qz-8WFh0mv
package main
import "log"
func myfunc(a int) bool{
func otherfunc(b int) bool{
return false
}
log.Println(otherfunc(2))
return true
}
func main() {
myfunc(1)
log.Println("here")
}
A similar function in Python would work. Why doesn't this work in Go?

You need to define the inner func as a local variable. Try this
func myfunc(a int) bool {
otherfunc := func(b int) bool {
return false
}
log.Println(otherfunc(2))
return true
}
Btw. otherfunc := func(b int) bool { is shorthand for var otherfunc func(int) bool = func(b int) bool {
Look at these examples
https://gobyexample.com/closures
https://gobyexample.com/variables

Related

Simplify casting in Go when taking any interface as a parameter

I have a struct like so,
//
// HandlerInfo is used by features in order to register a gateway handler
type HandlerInfo struct {
Fn func(interface{})
FnName string
FnRm func()
}
where I want to pass a func:
func StarboardReactionHandler(e *gateway.MessageReactionAddEvent) {
// foo
}
i := HandlerInfo{Fn: StarboardReactionHandler}
Unfortunately, this results in:
Cannot use 'StarboardReactionHandler' (type func(e *gateway.MessageReactionAddEvent)) as the type func(interface{})
I found this workaround:
func StarboardReactionHandler(e *gateway.MessageReactionAddEvent) {
// foo
}
func handlerCast(e interface{}) {
StarboardReactionHandler(e.(*gateway.MessageReactionAddEvent))
}
i := HandlerInfo{Fn: handlerCast}
Is there some way that I can simplify needing handlerCast, such as doing it inside my StarboardReactionHandler or in HandlerInfo? Maybe with generics or reflection? I basically just want to minimize the syntax / boilerplate that's required here.
you can use interface{}.(type)
follow is a exmple:
package main
import "fmt"
type HandlerInfo struct {
Fn func(interface{})
FnName string
FnRm func()
}
type MessageReactionAddEvent = func(a, b int) int
func StarboardReactionHandler(e interface{}) {
switch e.(type) {
case MessageReactionAddEvent:
fmt.Printf("%v\n", (e.(MessageReactionAddEvent))(1, 2))
}
}
func add(a, b int) int {
return a + b
}
func main() {
i := HandlerInfo{Fn: StarboardReactionHandler}
i.Fn(add)
}

How to check if all fields of a *struct are nil?

I'm not quite sure how to address this question, please feel free to edit.
With the first code block below, I am able to check if a all fields of a struct are nil.
In reality however, the values injected in the struct, are received as args.Review (see second code block below).
In the second code block, how can I check if all fields from args.Review are nil?
Try it on Golang Playground
package main
import (
"fmt"
"reflect"
)
type review struct {
Stars *int32 `json:"stars" bson:"stars,omitempty" `
Commentary *string `json:"commentary" bson:"commentary,omitempty"`
}
func main() {
newReview := &review{
Stars: nil,
// Stars: func(i int32) *int32 { return &i }(5),
Commentary: nil,
// Commentary: func(i string) *string { return &i }("Great"),
}
if reflect.DeepEqual(review{}, *newReview) {
fmt.Println("Nothing")
} else {
fmt.Println("Hello")
}
}
Try the second code on Golang Playground
This code below gets two errors:
prog.go:32:14: type args is not an expression
prog.go:44:27: args.Review is not a type
package main
import (
"fmt"
"reflect"
)
type review struct {
Stars *int32 `json:"stars" bson:"stars,omitempty" `
Commentary *string `json:"commentary" bson:"commentary,omitempty"`
}
type reviewInput struct {
Stars *int32
Commentary *string
}
type args struct {
PostSlug string
Review *reviewInput
}
func main() {
f := &args {
PostSlug: "second-post",
Review: &reviewInput{
Stars: func(i int32) *int32 { return &i }(5),
Commentary: func(i string) *string { return &i }("Great"),
},
}
createReview(args)
}
func createReview(args *struct {
PostSlug string
Review *reviewInput
}) {
g := &review{
Stars: args.Review.Stars,
Commentary: args.Review.Commentary,
}
if reflect.DeepEqual(args.Review{}, nil) {
fmt.Println("Nothing")
} else {
fmt.Println("Something")
}
}
If you're dealing with a small number of fields you should use simple if statements to determine whether they are nil or not.
if args.Stars == nil && args.Commentary == nil {
// ...
}
If you're dealing with more fields than you would like to manually spell out in if statements you could use a simple helper function that takes a variadic number of interface{} arguments. Just keep in mind that there is this: Check for nil and nil interface in Go
func AllNil(vv ...interface{}) bool {
for _, v := range vv {
if v == nil {
continue
}
if rv := reflect.ValueOf(v); !rv.IsNil() {
return false
}
}
return true
}
if AllNil(args.Stars, args.Commentary, args.Foo, args.Bar, args.Baz) {
// ...
}
Or you can use the reflect package to do your bidding.
func NilFields(x interface{}) bool {
rv := reflect.ValueOf(args)
rv = rv.Elem()
for i := 0; i < rv.NumField(); i++ {
if f := rv.Field(i); f.IsValid() && !f.IsNil() {
return false
}
}
return true
}
if NilFields(args) {
// ...
}

Golang multiple-value function composition

Short question to which I haven't found an answer on SO: how do I write composite function calls when an inner function has multiple return values?
Sub-question: can you cast just one of the returns from a multiple-value function without using a temp variable?
Example: http://play.golang.org/p/intnxkzSO1
package main
import "fmt"
func multiReturn() (int, int) {
return 0, 1
}
func noOp(a int) int {
return a
}
func main() {
// Too many arguments
fmt.Print(noOp(multiReturn()))
// multiple-value in single-value context
fmt.Print(string(multiReturn()))
}
You can have your outer function match the return values of the inner function
func multiReturn() (int, int) {
return 10, 1
}
func noOp(a, _ int) int {
return a
}
func main() {
fmt.Printf("%v\n", noOp(multiReturn())) // output: 10
fmt.Printf("%s", strconv.Itoa(noOp(multiReturn()))) // output: 10
}
On a side note string(int) will not work, you have to use the strconv package.
Go play
Another option would to use a variadic parameter.
func noOp(a ...int) int {
if len(a) > 0 {
return a[0]
}
return 0
}
For example,
package main
import "fmt"
func singleReturn() int {
s, _ := multiReturn()
return s
}
func multiReturn() (int, int) {
return 0, 1
}
func noOp(a int) int {
return a
}
func main() {
fmt.Print(noOp(singleReturn()))
fmt.Print(string(singleReturn()))
// Too many arguments
//fmt.Print(noOp(multiReturn()))
// multiple-value in single-value context
//fmt.Print(string(multiReturn()))
}
you can also return a function that returns multiple values.
func f() (int, int) {
return 1, 2
}
func g() (int, int) {
return f()
}

Golang use function that returns two variable

Assume there is a function that returns two variables.
func num(a,b int) (int,int) {
return a+b, a-b
}
http://play.golang.org/p/bx05BugelV
And assume I have a function that only takes one int value.
package main
import "fmt"
func main() {
fmt.Println("Hello, playground")
_, a := num(1, 2)
prn(a)
}
func num(a, b int) (int, int) {
return a + b, a - b
}
func prn(a int) {
fmt.Println(a)
}
http://play.golang.org/p/VhxF_lbVf4
Is there anyway I can only get the 2nd value (a-b) without having _,a:=num(1,2)??
Something like prn(num(1,2)[1]) <-- this won't work, but I'm wondering if there's a similar way
Thank you
Use a wrapper function. For example,
package main
import "fmt"
func main() {
_, a := num(1, 2)
prn(a)
prn1(num(1, 2))
}
func num(a, b int) (int, int) {
return a + b, a - b
}
func prn(a int) {
fmt.Println(a)
}
func prn1(_, b int) {
prn(b)
}
Output:
-1
-1

How to define a function type which accepts any number of arguments in Go?

I try to write a function which takes any other function and wraps a new function around it. This is what I have tried so far:
package main
import (
"fmt"
)
func protect (unprotected func (...interface{})) (func (...interface{})) {
return func (args ...interface{}) {
fmt.Println ("protected");
unprotected (args...);
};
}
func main () {
a := func () {
fmt.Println ("unprotected");
};
b := protect (a);
b ();
}
When I compile this I get the error:
cannot use a (type func()) as type func(...interface { }) in function argument
Why is a function without arguments not compatible to a function with a variable number of arguments? What can I do to make them compatible?
Update:
The protected function should be compatible with the original:
func take_func_int_int (f func (x int) (y int)) (int) {
return f (1)
}
func main () {
a := func (x int) (y int) {
return 2 * x
}
b := protect (a)
take_func_int_int (a)
take_func_int_int (b)
}
Types are pretty concrete in Go. You could try
a := func(_ ...interface{}) {
fmt.Println("unprotected")
}
func (...interface{}) does not mean "any function that takes any number of any kind of arguments", it means "only a function which takes a variable number of interface{} arguments"
Alternatively rather than func(...interface{}) you can just use interface{} and the reflect package. See http://github.com/hoisie/web.go for an example.
EDIT: Specifically, this:
package main
import (
"fmt"
"reflect"
)
func protect(oldfunc interface{}) (func (...interface{})) {
if reflect.TypeOf(oldfunc).Kind() != reflect.Func {
panic("protected item is not a function")
}
return func (args ...interface{}) {
fmt.Println("Protected")
vargs := make([]reflect.Value, len(args))
for n, v := range args {
vargs[n] = reflect.ValueOf(v)
}
reflect.ValueOf(oldfunc).Call(vargs)
}
}
func main() {
a := func() {
fmt.Println("unprotected")
}
b := func(s string) {
fmt.Println(s)
}
c := protect(a)
d := protect(b)
c()
d("hello")
}
Ouput is
Protected
unprotected
Protected
hello
EDIT: To answer the update
Like I said above, types are pretty concrete in Go. The protect function returns a type func(...interface{}) which will never be assignable to func(int)int. I think you're probably either over-engineering your problem or misunderstanding it. However, here's a highly discouraged code snippet that would make it work.
First change protect to also return values:
func protect(oldfunc interface{}) (func (...interface{}) []interface{}) {
if reflect.TypeOf(oldfunc).Kind() != reflect.Func {
panic("protected item is not a function")
}
return func (args ...interface{}) []interface{} {
fmt.Println("Protected")
vargs := make([]reflect.Value, len(args))
for n, v := range args {
vargs[n] = reflect.ValueOf(v)
}
ret_vals := reflect.ValueOf(oldfunc).Call(vargs)
to_return := make([]interface{}, len(ret_vals))
for n, v := range ret_vals {
to_return[n] = v.Interface()
}
return to_return
}
}
Then make a convert function:
func convert(f func(...interface{}) (func(int) int) {
return func(x int) int {
r := f(x)
return r[0].(int)
}
}
Then your call would look like
take_func_int_int(convert(b))
But I promise this isn't what you actually want to do.
Step back and try to rework the problem. I've completely killed type-safety in these examples. What are you trying to accomplish?
package main
import "fmt"
// Here's a function that will take an arbitrary number
// of `int`s as arguments.
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
// Variadic functions can be called in the usual way
// with individual arguments.
sum(1, 2)
sum(1, 2, 3)
// If you already have multiple args in a slice,
// apply them to a variadic function using
// `func(slice...)` like this.
nums := []int{1, 2, 3, 4}
sum(nums...)
}

Resources