Go Syntax and interface as parameter to function

前端 未结 2 1746
执念已碎
执念已碎 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:14

    An interface variable can hold values of any type that provides methods with the signatures from the interface declaration. Since interface{} doesn't specify any methods, such a variable can store values of any type.

    The method then goes on to use a type assertion to check that other is actually a *ContactRecord value (it will panic otherwise).

    You might then ask why the method isn't declared as taking a *ContactRecord argument then. The most likely reason is so that the *ContactRecord type implements some interface with a Less method with that signature.

提交回复
热议问题