4 ms·
Can you help me understand this code on interfaces? If you were calling (CartStore.GetById()) where does (*cart.Cart) come from? I don't see any logical conne
by rustyboy 6y ago
Can you help me understand this code on interfaces? If you were calling (CartStore.GetById()) where does (*cart.Cart) come from? I don't see any logical connection between these two.
type Cart interface {
GetById(ID string) (*cart.Cart, error)
Put(cart *cart.Cart) (*cart.Cart, error)
}
// A type that implements the interface :
type CartStore struct{}
func (c *CartStore) GetById(ID string) (*cart.Cart, error) {
// implement me
}
func (c *CartStore) Put(cart *cart.Cart) (\*cart.Cart, error){
// implement me
}
- maximilienandi 6y agoHello rustyboy, first thanks for your feedback. I think that there is a mistake in the name of the interface type. It should not be `Cart` but something else. Like `CartStorage`. A type that implement this CartStorage interface can be named `MySQLCartStorage` or `DynamoDBCartStorage`. Each database engine responsible for the storage will have a different implementation. The interface is here to define a contract, a set of behaviors that you should implement. I will definitely change that
- rustyboy 6y agoLet me just clarify, sorry i'm from python, so not very familiar but this feels like a "circular reference". You're implementing a struct CartStore which has methods GetById, and Put. Because interfaces (or contracts) are implicit then it's automatically considered a Cart. What I don't understand is the return types of these functions, a pointer to a cart's cart member? or an error.
- maximilienandi 6y agoInterfaces in Go are implicitely implemented. It means that if a type has the methods defined in the interface, then it implements the interface. I will update the example because it's confusing ! If you have some time come to the speak with me in the chatbox on the website I can help you understand this.
- Jtsummers 6y agocart.Cart package.NameInPackage So the name Cart is an interface, the function/method signatures are indicating that a Cart is being returned but being explicit about the package the interface belongs to with cart.Cart. It's made more confusing since the name cart (lower-c) is being used for both a member variable and the package name in the signature of Put, and it looks like the package name doesn't show up on an explicit line in that chapter to help clarify it.