<\/span><\/h1>\n\n\n\nA function in Go can be called in go as below<\/p>\n\n\n\n
results := sum(2, 3)<\/code><\/pre>\n\n\n\nSome points to note about calling a function<\/p>\n\n\n\n
- If the function of some other package is being called then it is necessary to prefix the package name. Also please note that across packages only those function can be called which are exported meaning whose name start with capital letter<\/li><\/ul>\n\n\n\n
- With in the same package the function can directly be called using its name suffixed by ()<\/li><\/ul>\n\n\n\n
<\/span>Function Parameters<\/strong><\/span><\/h1>\n\n\n\n- As mentioned above function can have zero or more arguments.<\/li><\/ul>\n\n\n\n
- type for the consecutive same types can be specified only once. For example above sum function can also be written as<\/li><\/ul>\n\n\n\n
func sum(a, b int)<\/code><\/pre>\n\n\n\n- A copy of all the arguments is made while calling a function.<\/li><\/ul>\n\n\n\n
<\/span>Return Values<\/strong><\/span><\/h1>\n\n\n\n- As mentioned above a function can have one or more return values. Assume there is a function sum_avg that returns two values: Sum and Average. Example of multiple return values<\/li><\/ul>\n\n\n\n
func sum_avg(a, b int) (int, int)<\/code><\/pre>\n\n\n\n- As a convention error is returned as the last argument in a function. Example<\/li><\/ul>\n\n\n\n
func sum(a, b int) (int, error)<\/code><\/pre>\n\n\n\n- Collecting multiple return values in the caller function. In below example<\/li><\/ul>\n\n\n\n
result, err := sum(2, 3) <\/code><\/pre>\n\n\n\n<\/span>Named Return Values<\/strong><\/span><\/h2>\n\n\n\nA go function can have named return values. With named return values , the return values did not need to be initialised in the function. <\/strong>The named variables are specified in the signature itself. Without named values, only return type is specified. It is also ok to name some of the return values. For other return values only type can be specified. <\/p>\n\n\n\n- See example below: result<\/strong> is the named return value<\/li><\/ul>\n\n\n\n
func sum(a, b int) (result int)<\/code><\/pre>\n\n\n\n- With named return values, type of the consecutive same types can be specified only once<\/li><\/ul>\n\n\n\n
func sum_avg(a, b int) (sum, avg int)<\/code><\/pre>\n\n\n\n<\/span>Function Usages<\/strong><\/span><\/h1>\n\n\n\n