# Function literals

### October 12, 2023

This week’s episode of the Cup o’ Go podcast is out! Check out the latest Go news, and an interview with Tim Stiles about hacking ðŸ§¬ DNA with Go.

We should all be familiar with functions, and how to create them in Go:

``````func Foo() { /* ... */ }
``````

But we can also have function literals…

## Function literals

A function literal represents an anonymous function. Function literals cannot declare type parameters.

``````FunctionLit = "func" Signature FunctionBody .
``````
``````func(a, b int, z float64) bool { return a*b < int(z) }
``````

It’s interesting to note that function literalls cannot declare type parameters. In other words, they can’t be generic. This is because a function literal is already instantiated, and as we’ve discussed previously, instantiation is the process by which a generic function is resolved to reference its concrete types.

A function literal can be assigned to a variable or invoked directly.

``````f := func(x, y int) int { return x + y }
func(ch chan int) { ch <- ACK }(replyChan)
``````

Not mentioned here, but relevant, is that you can also assign normal (non literal) functions to variables.

``````func Foo() {}

var f = Foo // f is a variable of type func()
``````

But to do this with a generic function requires instantiating it at the time it is assigned to a variable:

``````func Foo[T any](i T) { /* ... */ }

var f = Foo // cannot use generic function Foo without instantiation
var f = Foo[int] // valid
``````

Quotes from The Go Programming Language Specification Version of August 2, 2023