Go Syntax and interface as parameter for function

I am new to Go programming language and recently came across the following code:

func (rec *ContactRecord) Less(other interface{}) bool { return rec.sortKey.Less(other.(*ContactRecord).sortKey); } 

However, I do not understand the meaning behind the signature of the function. It takes an interface as a parameter. Could you explain to me how this works? Thanks

+6
source share
2 answers

Go uses interfaces to generalize types. Therefore, if you need a function that accepts a specific interface you write

 func MyFunction(t SomeInterface) {...} 

Each type that satisfies SomeInterface can be passed to MyFunction .

Now SomeInterface might look like this:

 type SomeInterface interface { SomeFunction() } 

To satisfy SomeInterface , the type implementing it must implement SomeFunction() .

If you need an empty interface ( interface{} ), the object should not implement any method that should be passed to the function:

 func MyFunction(t interface{}) { ... } 

This function above accepts each type as all types implement an empty interface .

Return type

Now that you can have all possible types, the question arises as to how to return the type back was actually set earlier. An empty interface does not provide any methods, so you cannot name anything of that value.

To do this, you need type statements: let the runtime check if type X is in the value Y and convert it to this type, if so.

Example:

 func MyFunction(t interface{}) { v, ok := t.(SomeConcreteType) // ... } 

In this example, the input parameter t is considered to be SomeConcreteType . If t actually has type SomeConcreteType , v will contain an instance of this type, and ok will be real. Otherwise, ok will be false. See type specifications for details.

+12
source

An interface variable can store any type of value that provides methods with signatures from the interface declaration. Since interface{} does not specify any methods, such a variable can store values โ€‹โ€‹of any type.

The method then continues to use the type assertion to verify that other actually *ContactRecord (otherwise it will panic).

You may then ask why the method is not declared as accepting *ContactRecord . The most likely reason is that the *ContactRecord type implements some interface using the Less method with this signature.

+4
source

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


All Articles