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
Yes, you can pass Interface as a parameter in the function.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With