What is the use of defining Go methods from defining structures?

Go allows you to define methods separately from the structure / data type on which they work. Does this simply mean flexibility in placing method definitions or something more?

I heard that the Go struct / methods system is compared with a monkey patch, but if I understand correctly, then you really cannot add methods to an existing type (struct), since the methods must be in the same package as the type, i.e. You can patch monkeys only those types that are under your control anyway. Or am I missing something?

In what cases do you define a type and its methods in separate source files (or in different parts of the same source file)?

+6
source share
3 answers

This is the advantage of Go over type languages: you can arrange your files as you like:

  • you can combine all of these functions, even if there are many types of receivers
  • you can split a file that would otherwise be too large

As often, Go did not add a restriction that was useless. So the answer could also be “why not”?

you really cannot add methods to an existing type (struct), since the methods must be in the same package as the type

If you could, you might not be able to determine which function to call in the case of the same function name used in the same structure in two different packages. Or it will make some packages incompatible.

+9
source

This is (in part, possible), because in Go you can have methods for any type, and not just for the structure:

type Age uint func (a Age) Add(n Age) Age { return a + n } 

It is also a way to add methods to an existing type. What you do is define a new type based on this existing type and add methods as you like.

+7
source

A monkey patch is not possible. The type you define must be in the same package.

What you can do is define functions and methods, wherever you are inside the package. This does not matter much if the type definition is in the same file as the method definition for the type.

This allows you to group all type definitions in one file and implement the method implementation in another. Perhaps with the help of another helper that the methods need.

+6
source

Source: https://habr.com/ru/post/927831/


All Articles