Named Parameters in Golang

Named return parameters are the values a function returns, with their names defined in the function signature. By default, Go functions return their values in the defined order.

Go does not support named parameters directly like some other languages, such as Python.

Diagram of Named Parameters in Go

However, you can achieve similar functionality by using a “struct” to define the parameters and then passing an instance of that struct to the function.

With named return parameters, developers can assign names to the returned values, making a function call more explicit and easier to understand.

package main

import (
  "fmt"
)

type CalculateAreaParams struct {
  Width float64
  Height float64
}

func CalculateArea(params CalculateAreaParams) float64 {
  return params.Width * params.Height
}

func main() {
  params := CalculateAreaParams {
    Width: 10.0,
    Height: 21.0,
  }

  area := CalculateArea(params)
  fmt.Println("Area:", area)
}

Output

Area: 210

That’s it.

1 thought on “Named Parameters in Golang”

Comments are closed.