Go Syntax and interface as parameter to function

前端 未结 2 1719
执念已碎
执念已碎 2021-01-31 19:17

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

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


        
2条回答
  •  再見小時候
    2021-01-31 20:22

    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.

提交回复
热议问题