Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Definition
3.
Examples
3.1.
Call By Value
3.1.1.
Code
3.1.2.
Output
3.2.
Call by Reference
3.2.1.
Code
3.2.2.
Output
4.
Features
5.
Anonymous Function
5.1.
Code
5.2.
Output
6.
Parameter Without a Type
6.1.
Code
6.2.
Output
7.
Frequently Asked Questions
7.1.
Is Golang a functional or object-oriented language?
7.2.
Is Golang compiled or interpreted?
7.3.
Is Go lacking in classes?
7.4.
Why does Go lack inheritance?
8.
Conclusion
Last Updated: Mar 27, 2024

Go Function Arguments

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Go is rapidly becoming one of the most widely used programming languages: It now ranks 10 in the TIOBE programming community index and is used to power prominent applications such as Kubernetes, Docker, and Heroku CLI.

There are numerous features inside the language that make it extremely interesting. But, as one of its designers, Rob Pike, pointed out, one of the critical reasons for Go's popularity is its simplicity.

In this article, We will discuss Go's simple and essential parts. We will discuss the definition, examples, and features of Function Arguments in Golang. We will see how to pass arguments. We will also discuss the Parameter without a name and the Parameter without a type.

Definition

A function is a small block of code dedicated to doing a particular action based on some input data. We establish a function that allows us to conduct such an operation anytime and wherever we wish by supplying specific input data.

These input values are entirely optional and provide additional information to a function. The execution of a function may or may not give any output.

The func keyword in Go is used to define a function.

func definition() {
    fmt.Println("Defining a function using 'func' Keyword.")
}

This function can be invoked from anywhere in the program's function body. For example, We have a function named ‘definition’ that prints some characters to standard output.

package main
import "fmt"
func definition() {
    fmt.Println("Defining a function using 'func' Keyword.")
}
func main() {
    definition()
}

Output:

A function can take input values for its execution, as previously mentioned. Arguments are the input values provided in a function call. We can pass one or more arguments to a function.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples

There are two ways to pass arguments to the function in Golang.

  • Pass by Value or Call by Value.
  • Pass By Reference or Call By Reference.

By default, Golang passes the arguments to the function via call by value.

Call By Value

Actual parameter values are copied to function formal parameters in this parameter passing, and the two types of parameters are kept in different memory locations. As a result, any changes made inside functions are not reflected in the caller's actual parameters.

Code

package main
import "fmt"
// function which changes the value
func change(X int) {
    X = 100
}  
// Main function
func main() {  
    var X int = 31  
    fmt.Printf("Before the Function Call, value of X is = %d", X)
    // call by value
    change(X   
    fmt.Printf("\n After the Function Call, value of X is = %d", X)
}

Output

Here, we can see the value of X before and after the function call is the same. It cannot be changed using the change function.

Call by Reference

We pass the variable's address rather than its values when invoking it. We will utilise the concept of pointers here. Because the actual and formal parameters both refer to the same locations, any type of changes performed within the function are reflected in the caller's actual parameters.

Code

package main  
import "fmt"
// function which changes the value
func change(X *int) {
    *X = 100
} 
// Main function
func main() {
    var X int = 31
    fmt.Printf("Before the Function Call, value of X is = %d", X)
    // call by Reference
    change(&X)
    fmt.Printf("\n After the Function Call, value of X is = %d", X)
}

Output

Features

Functions and methods in Go can return multiple values, which is a unique feature. This form can be used to fix a pair of problematic C programming idioms: in-band error returns like -1 for EOF and altering an argument given by the address.

A negative count indicates a write error in C, with the error code hidden in a volatile location. Write can return a count and an error in Go.

The Write method on files from package os has the following signature:

func (file *File) Write(b []byte) (n int, err error)

For returning multiple values directly after the function parameter parentheses, we must provide the return types of the values inside the parenthesis. For example;

package main
import "fmt"
func swap(a, b string) (string, string) {
   return b, a
}
func main() {
   x, y := swap("Ninjas", "Coding")
   fmt.Println(x, y)
}

When the above code is compiled and run, the following result is obtained:

Anonymous Function

An anonymous function is a unique feature of the Go programming language. A function with no name is known as an anonymous function. It comes in handy when you need to write an inline function.

Code

// to create an anonymous function
package main
import "fmt"
func main() {  
    // Anonymous function
   func(){
      fmt.Println("Example of Anonymous Function.")
  }()   
}

Output

Parameter Without a Type

When a function's parameters all have the same type, the type can be omitted for some of them; that is, the type can only be stated once.

Code

package main
import "fmt"
func sum(a int, b int) int {
    return a + b
}
func sub(a, b int) int {
    return a - b
}
func main() {
    fmt.Println(sum(6, 2))
    fmt.Println(sub(6, 2))
}

Output

Frequently Asked Questions

Is Golang a functional or object-oriented language?

Go (or "Golang") is a post-OOP programming language that borrows the Algol/Pascal/Modula language family's structure (packages, types, and functions). Object-oriented paradigms, however, are still crucial in Go for designing a programme clearly and understandably.

Is Golang compiled or interpreted?

Golang is a compiler-based language that may be readily compiled on a development machine for any target operating System, including Linux and Mac. When a Golang project is built, it becomes a self-contained executable that can be run on the target machine without any other software.

Is Go lacking in classes?

Although Go does not have classes in the classic sense, it does have struct types, which are far more powerful than their C counterparts.

Why does Go lack inheritance?

Because Golang lacks classes, inheritance is accomplished using struct embedding. We can't directly extend structs; instead, we employ the composition idea, in which the struct is used to create other objects. So, in Golang, there is no concept of inheritance.

Conclusion

This article has discussed Function Arguments' definition, examples, and features in Go. We ran through how to pass arguments. We also discussed the Parameter without a name and the Parameter without a type. You can learn related concepts like Object-oriented paradigmsoperating systems, classesinheritance, etc., at the Coding Ninjas Studio blogs vertical.

We hope this article has helped you. You can check out this article on Exploring the dynamics of Golang. To understand the usefulness of Golang, read this article Why Golang is so famous among engineers.

 
Recommended Readings: 

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

Previous article
Main and Init Functions in Golang
Next article
Go Functions Returning Multiple Values
Live masterclass