How to Create Function in Go: Syntax and Examples
In Go, you create a function using the
func keyword followed by the function name, parameters in parentheses, and the function body in braces. Functions can return values by specifying return types after the parameters.Syntax
The basic syntax to create a function in Go is:
- func: keyword to declare a function.
- functionName: the name you give your function.
- parameters: inputs inside parentheses, each with a name and type.
- return type: optional, specifies the type of value the function returns.
- function body: code inside curly braces that runs when the function is called.
go
func functionName(parameterName parameterType) returnType {
// function body
}Example
This example shows a function named add that takes two integers and returns their sum.
go
package main import "fmt" func add(a int, b int) int { return a + b } func main() { result := add(3, 5) fmt.Println("Sum:", result) }
Output
Sum: 8
Common Pitfalls
Common mistakes when creating functions in Go include:
- Forgetting to specify parameter types.
- Not returning a value when the function signature requires one.
- Using the wrong return type or mismatched return statements.
- Not calling the function after defining it.
go
package main import "fmt" // Wrong: missing parameter types // func greet(name) { // fmt.Println("Hello", name) // } // Correct: func greet(name string) { fmt.Println("Hello", name) } func main() { greet("Alice") }
Output
Hello Alice
Quick Reference
| Part | Description | Example |
|---|---|---|
| func | Keyword to declare a function | func |
| functionName | Name of the function | add |
| parameters | Input variables with types | a int, b int |
| return type | Type of value returned | int |
| function body | Code inside braces | { return a + b } |
Key Takeaways
Use the func keyword followed by the function name and parameters to create a function in Go.
Always specify parameter types and return types if your function returns a value.
The function body contains the code that runs when the function is called.
Common errors include missing parameter types and mismatched return statements.
Call your function in main or other functions to execute its code.