Golang Receiver Functions -2


In this lesson, we will talk about receiver functions over type structures.

For example, it is quite similar to the C# extensions feature, which C# users are not far from.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

If we do remember, there was an extension method that we defined as static in C#. Here, as a type safe, we add the variable of the type we specified with the "this" parameter as a method and send the content of the variable directly into the method.


namespace ExtensionMethods { public static class MyExtensions { public static void PrintConsole(this string message) { Console.Writeln(message) } } }


Main methodu

static void Main(String[] args) { String extensionTest = "demo";

extensionTest.PrintConsole();

}

Our console application will print "demo".

Golang receiver functions are also quite similar.

https://medium.com/@adityaa803/wth-is-a-go-receiver-function-84da20653ca2

Now, let's take a look at the code block I gave the link above.

package main
import "fmt"


// We create the structure that the Receiver method will accept. // Notice that, unlike our example in C#, this is a structure.

type person struct {
name string
age int
} // If we come to the breaking point, inside the print method // We define the person structure to accept it. // Note that this will not be a parameter, but an extension of the struct itself.
 

func (p person) print() {
fmt.Printf("%s is of %d years \n", p.name, p.age)
}
// We created the Person structure and this structure is the print function can be called with.
func main() {
alex := person{
name: "Alex",
age: 18,
}
alex.print()
}

Have a good work.


  



Yorumlar

Bu blogdaki popüler yayınlar

IONIC BAŞLANGIÇ

Cannot resolve the collation conflict between “Turkish_CI_AS” and “SQL_Latin1_General_CP1_CI_AS” in the equal to operation

Golang working with interfaces and functions -3