For a common struct as a receiver, there is no difference between a value and a pointer.
(The following code is excerpt from Go in Action Chinese version)
Type Defaultmatcherstruct{}//method is declared as a recipient using a value of type DefaultmatcherFunc (M Defaultmatcher) Search (feed *feed, searchtermstring)//declares a pointer to a value of type DefaultmatcherDM: =New(Defaultmatch)//The compiler will undo the reference to the DM pointer and call the method with the corresponding valueDm. Search (Feed,"Test")//method is declared as a recipient using a pointer to a value of type DefaultmatcherFunc (M *defaultmatcher) Search (feed *feed, searchtermstring)//declares a value of type DefaultmatchervarDM Defaultmatch//the compiler automatically generates pointers to reference DM values, using pointers to call methodsDm. Search (Feed,"Test") uses an empty structure to declare a struct type named Defaultmatcher. Empty structure
When you create an instance, no memory is allocated. This structure is ideal for creating types that do not have any state. For the default matching device
, there is no need to maintain any state, so we can just implement the corresponding interface.
because most methods need to maintain the state of the recipient's value after being called, a best practice is to declare the recipient of the method as a pointer . for the Defaultmatcher type, the value is used as the recipient because creating a value of type Defaultmatcher does not require memory allocation. Because Defaultmatcher does not need to maintain state, it does not require a recipient in the form of pointers.
Unlike a method called directly by a value or a pointer, if a method is called by a value of an interface type , the rule is very different, and the method used as the recipient declaration can only be called when the value of the interface type is a pointer . A method that uses a value as a recipient declaration can be called when the value of an interface type is a value or a pointer .
//method is declared as a recipient using a pointer to a value of type DefaultmatcherFunc (M *defaultmatcher) Search (feed *feed, searchtermstring)//to invoke a method by a value of type interfacevarDM defaultmatchervarMatcher Matcher = DM//Assigning a value to an interface typeMatcher. Search (Feed,"Test")//using values to invoke an interface method>go buildcannot use DM (type Defaultmatcher) asType MatcherinchAssignment//method is declared as a recipient using a value of type DefaultmatcherFunc (M Defaultmatcher) Search (feed *feed, searchtermstring)//to invoke a method by a value of type interfacevarDM defaultmatchervarMatcher Matcher = &DM//assigning pointers to interface typesMatcher. Search (Feed,"Test")//using pointers to invoke interface methods>Go buildbuild Successful