Methods on Non-Struct Type

Learn via video courses
Topics Covered

Overview

The Go programming language provides some object-oriented features. A method is one of these features. Go methods are similar to the Go functions. The only difference between a Go method and a Go function is that the method contains a receiver argument between the func keyword and the method name. The method can access the receiver's properties using the receiver argument. A receiver can be either struct or non-struct. When you write code, you must include the receiver and receiver type in the same package.

Introduction

Go methods are similar to the Go functions. The only difference between a Go method and a Go function is an extra argument that is added after the func keyword to specify the method's receiver. The receiver argument of the method has a name and a type. It can be either struct or non-struct. The receiver and receiver type must be in the same package when you write your code. The method can access the receiver's properties by using the receiver argument.

Syntax

The syntax of the Go method is given below.

Non-struct Methods

In Go Language, It is also possible to define methods on non-struct type receiver as long as the type and method definitions are in the same package. But when the definition of the receiver type and the definition of the method are present in multiple packages, such as int, string, and so on, the compiler will throw an error because they are defined in multiple packages.

Example of Non-struct Methods

Here is a Go program demonstrating the method with a non-struct type receiver.

Code

Output

Explanation of the Output

In the example of Non-struct Methods, before defining the addition method with val as the receiver, we have created a type alias val for int. In the main function of the code, we have taken two inputs, num1 and num2, and called the addition method using the syntax num1.addition(num2). When we run this program, it prints "The sum of the numbers: 47".

Conclusion

  • In the Go language, a function is a block of code that takes a few parameters as input and produces some output.
  • The Go language supports various object-oriented features. A method is one of these features.
  • Go methods are similar to the Go functions. The only difference between a Go method and a Go function is that the method contains a receiver argument between the func keyword and the method name.
  • The method can access the receiver's properties using the receiver argument.
  • In Go Language, It is possible to define methods on non-struct type receiver as long as the type and method definitions are in the same package.