The project needs to port some code to Golang. It was very comfortable to write in Laravel encapsulated before, and it can only be automatically implemented in Golang.
At the beginning, I thought about using interface implementation, but encountered a pitfall. The combination in Golang is a false inheritance
package main import "fmt" type Person interface { Say() Name() } type Parent struct { } func (s *Parent) Say() { ("i am " + ()) } func (s *Parent) Name() string { return "parent" } type Child struct { Parent } func (s *Child) Name() string { return "child" } type Child1 struct { Parent } func main() { var c Child // i am parent () var c1 Child1 // i am parent () }
- As mentioned above () code, it should be output i am child in other languages, but Golang is different. You can only understand after checking Golang's information./ref/spec#Selectors
- Generally speaking, when calling the f method or property, it will be called from the current or nested anonymous structure from shallow to deep, without looking for the superior.
- For example, if child1 does not have a Say method, it will enter the anonymous structure Parent to find the Say method, and then call it
- And child does not have a Say method, and also calls Parent's Say method. At this time, Say is called through Parent. When the method is called in Say, child cannot be found, so Parent's Name method will still be called
- Then I sorted out and wrote a general remember method with my colleagues.
import ( "context" "encoding/json" "fmt" "/gin-gonic/gin" "time" ) // Redis operation has been simplifiedfunc CacheGet(c , t interface{}, cacheKey string, callQuery func() error) error { // Here we get data through redis. If data exists, then return directly dataBytes, err := (c, cacheKey).Bytes() if err == nil { if err := (dataBytes, t); err == nil { return nil } } // When redis has no data, then call this method to modify t, if err := callQuery(); err != nil { return err } // Here you store the modified t to redis, and you can use the cache next time you use it dataBytes, err = (t) if err == nil { (c, cacheKey, dataBytes, *30) } return nil } func handle(c *) { var model err := ( (), &model, ("cache_xxx:%s", ("id")), func() error { return (&model) }, ) }
This is the article about implementing the Cache::remember method in Golang. For more related content on Golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!