Basic Function Syntax
In Go, functions are defined using thefunc keyword, followed by the function name, parameters, return type, and body.
- Takes two parameters
aandb, both of typeint - Returns a single
intvalue - Uses an explicit
returnstatement
Go requires explicit returns. Unlike some languages, Go won’t automatically return the value of the last expression.
Parameter Type Shorthand
When multiple consecutive parameters share the same type, you can omit the type name for all but the final parameter:Calling Functions
Functions are called using the familiarname(args) syntax:
Complete Example
Best Practices
Use descriptive function names
Use descriptive function names
Choose names that clearly describe what the function does. Use camelCase for unexported functions and PascalCase for exported functions.
Keep functions focused
Keep functions focused
Each function should do one thing well. If a function is doing too much, consider breaking it into smaller functions.
Always use explicit returns
Always use explicit returns
Go requires explicit return statements, which makes code more readable and less prone to errors.
Key Takeaways
- Functions are defined with the
funckeyword - Parameter types can be shared using shorthand syntax
- Go requires explicit
returnstatements - Functions are called using standard
name(args)syntax