为什么可以将结构作为函数的接口传递?

I have some example code that takes an interface as an input as below.

type RouteGuideServer interface {
        ...
}

func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) {
    s.RegisterService(&_RouteGuide_serviceDesc, srv)
}

That is all fine and good, but then when implementing this server we have the following code which gives a struct (that implements the interface) to the function as below.

type routeGuideServer struct {
        ...
}

...

pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})

I would expect that an error is thrown when given the wrong type.. why does this work? I feel that this shouldn't work?

I would appriciate any feedback, Thanks!

An interface defines a set of methods. Any type that has those methods "implements" that interface.

In your case, you have a struct type implementing all the methods of an interface. That means values of that struct type can be used wherever such an interface is needed. When you pass a struct value to a function like you did, the complier will check if the value implements all the functions of the interface, and if it does, send the value as an interface to the function. Outside the function you have your struct value, but inside the function, you can only see the functions of that interface. You can, however, make a type assertion and recover the value of that interface:

func (f interfaceType) {
   if k, ok := f.(myType); ok {
      // Here, k is the value of the interface, which is of type "myType"
   }

This works because *routeGuideServer implements RouteGuideServer. If wrongType doesn't implement RouteGuideServer, you'll get an error:

wrongType does not implement RouteGuideServer(missing "some" method)

example