Go Function Parameters and Arguments

Functions in Go can accept data in the form of parameters. These parameters act as variables within the function and allow data to be passed and processed. When you invoke a function and provide values, these are referred to as arguments.

Tutorials dojo strip

Parameters and their types are specified within parentheses () following the function name. Multiple parameters should be separated with commas.



Syntax for Parameters

func FunctionName(param1 type, param2 type, param3 type) {
  // code to execute
}




Example 1: Function with a Single Parameter

package main
import ("fmt")

func motorcycleBrand(brand string) {
  fmt.Println("This motorcycle brand is", brand)
}

func main() {
  motorcycleBrand("Ducati")
  motorcycleBrand("Yamaha")
  motorcycleBrand("Honda")
}

Output:

This motorcycle brand is Ducati
This motorcycle brand is Yamaha
This motorcycle brand is Honda

Explanation:

  • motorcycleBrand is a function with one parameter, brand.
  • When the function is called (e.g., motorcycleBrand("Ducati")), the argument "Ducati" is passed into the brand parameter.


Difference Between Parameters and Arguments

  • Parameters: Declared in the function definition (e.g., brand in the example above).
  • Arguments: The actual values passed to the function when called (e.g., "Ducati", "Yamaha", "Honda").




Example 2: Function with Multiple Parameters

Functions can accept multiple parameters of different types. This example includes two parameters: brand (a string) and rating (an int).

package main
import ("fmt")

func motorcycleInfo(brand string, rating int) {
  fmt.Println("The motorcycle brand", brand, "has a rating of", rating, "stars.")
}

func main() {
  motorcycleInfo("Suzuki", 5)
  motorcycleInfo("Honda", 4)
  motorcycleInfo("Yamaha", 3)
}

Output:

The motorcycle brand Suzuki has a rating of 5 stars.
The motorcycle brand Honda has a rating of 4 stars.
The motorcycle brand Yamaha has a rating of 3 stars.

Notes on Multiple Parameters

  • The number of arguments in the function call must match the number of parameters in the function definition.
  • Arguments must be passed in the same order as the parameters are declared.
Tutorials dojo strip
Scroll to Top