Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Syntax and interface as parameter to function

Tags:

I am new to Go programming language and recently encountered 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 function signature. It accepts an interface as a parameter. Could you please explain me how this works ? Thanks

like image 223
kaalobaadar Avatar asked Dec 01 '13 16:12

kaalobaadar


People also ask

Can an interface be passed as a parameter?

Yes, you can pass Interface as a parameter in the function.

Can Golang interface have functions?

Use of Interface: You can use interface when in methods or functions you want to pass different types of argument in them just like Println () function. Or you can also use interface when multiple types implement same interface.

How do you call an interface in Golang?

When you call r. Area() , go executes the function func (r Rect) Area() uint64 . With the line r.F = *n , you assign the interface Second to First (they are equivalent, no problem). However, if you try to call r.F.Area() it will panic because F is not a type that implements First, it is First.

What does interface {} mean in Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.


1 Answers

Go uses interfaces for generalization of types. So if you want a function that takes a specific interface you write

func MyFunction(t SomeInterface) {...} 

Every type that satisfies SomeInterface can be passed to MyFunction.

Now, SomeInterface can look like this:

type SomeInterface interface {     SomeFunction() } 

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

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

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

This function above will take every type as all types implement the empty interface.

Getting the type back

Now that you can have every possible type, the question is how to get the type back that was actually put in before. The empty interface does not provide any methods, thus you can't call anything on such a value.

For this you need type assertions: let the runtime check whether there is type X in value Y and convert it to that type if so.

Example:

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

In this example the input parameter t is asserted to be of type SomeConcreteType. If t is in fact of type SomeConcreteType, v will hold the instance of that type and ok will be true. Otherwise, ok will be false. See the spec on type assertions for details.

like image 172
nemo Avatar answered Sep 17 '22 15:09

nemo