Methods in Golang

A method represents a function associated with a particular type. Methods are defined in the same way as regular functions, except that the definition You must also specify a receiver. The receiver is a parameter of the type to which the method is attached:

func(parameter_name, receiver_type), method_name(s), (return_results_types){
    Method_body
}

Let's say we define a named type that represents a slice of strings:

type books []string

To derive all elements from a slicer, we can define the following method:

func (list books) print(){ 
    for _, val := range l{
        fmt.Println(val)
    }
}

The part that lies between the keyword and the method name and represents the definition of the recipient, for which this method will be defined:func(list books).
Using the recipient parameter (in this case, list), we can address the recipient. For example, in our case, the receiver represents a slice (a set of objects). With the help of the for loop, you can go through this slice and display all its elements to the console.

Since print represents a method that is defined for the library type, and not a regular function, we can call this method on any object of type library:

var list books = books{ "Rust", "Golang", "PostgreSQL" }
list.print()

list is an object of type books, so we can call the print method on it. In this case, the list object will be the value that will be passed to the print function via the (list books).

Structure Methods

Similarly, we can define methods for structures:

package main

import "fmt"

type book struct {
	title      string
	pageNumber int
}

func (b book) printBook() {
	fmt.Println("The book name :", b.title)
	fmt.Println("The number of pages :", b.pageNumber)
}

func (b book) code(c string) {
	fmt.Println(b.title, "ест", c)
}

func main() {

	var postgres = book{title: "Learn SQL with Postgres ", pageNumber: 1000}
	postgres.printBoook()
	postgres.code("Learn by examples and practice! ")
}

The console output of this program is:

The book name : Learn SQL with Postgres 
The number of pages : 1000
Learn SQL with Postgres  ест Learn by examples and practice! 

In this case, two functions are defined for the book structure: printBook and code. The print function displays information about the current book object. And the function code mimics the way you should learn. Each of these functions defines the object and type of structure to which the function belongs:

func (b book) function name

With the help of the b object, we can access the properties of the book structure. Otherwise, these are normal functions that can take parameters and return a result.

To refer to the functions of the structure, a variable of the structure is specified and the function is called through a period.