Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function with parameters to time.AfterFunc

Tags:

People also ask

How do you pass a function as parameters in Go language?

Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.

Where do parameters go in a function?

A parameter is the variable listed inside the parentheses in the function definition.

How do you write a function in Golang?

Syntax. In the Go language, we declare a function by typing the func keyword. After typing in the func keyword, we have to write the name of our function. Following that, we list the parameters (if any are present), and then list the return type of the function being defined.

What is an argument in Golang?

Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program. In Golang, we have a package called as os package that contains an array called as “Args”.


time.AfterFunc() accepts a duration and a function to be executed when that duration has expired. But the function cannot be a function that accepts parameters.

For example: The following function cannot be passed:

func Foo (b *Bar) {}

Although, it is possible to initialize a new function that calls the above one and then pass it:

f := func() {
    Foo(somebar)
}
timer := time.AfterFunc(1*time.Second, f)

Should this really be done this way?
Why does time.AfterFunc not accept any functions that accept parameters?
Do there exist other/better ways to do this?