What parameters do Golang decorator functions have?
php editor Baicao will introduce to you the parameters of the Golang decorator function. In Golang, a decorator function is a special function that can be used to wrap other functions and add extra functionality to them. Decorator functions usually have three parameters: the original function, the parameters of the decorator function, and the return value. The original function is the function that needs to be decorated. The parameters of the decorator function can be of any type and can be used to pass additional parameters to the decorator function. The return value is usually a function that replaces the execution of the original function. Through these parameters, we can implement various flexible decorator modes, add different functions to functions, and improve the reusability and scalability of the code.
Question content
I want to use setters on several methods of adminapi, such as update
. To do this, I created a method type that can be matched with other methods.
Should I use an interface instead of func type
?
type adminapi struct { } type toadminctx func(ctx context.context, req interface{}) (interface{}, error) func (a adminapi) adminm2msetter(s toadminctx) toadminctx { return func(ctx context.context, arg interface{}) (interface{}, error) { m2mprincipal, _ := a.getm2mprincipal(ctx) ctxm2m := extlib.setprincipal(ctx, m2mprincipal) return s(ctxm2m, arg) } } func (a adminapi) update(ctx context.context, req *reqtype) (resptype, error) {}
updateWithAdminCtx := a.adminAPI.AdminM2MSetter(s.adminAPI.Update) // ERROR => cannot use s.adminAPI.Update (value of type func(ctx // context.Context, req *ReqType) (RespType, error)) as grpcAdmin.ToGetAdminCtx value in // argument to s.adminAPI.AdminM2MSetter _, err := updateWithAdminCtx(ctx context.Context, req *ReqType)
Solution
I think the error you are encountering is self-explanatory:
a.adminapi.adminm2msetter(s.adminapi.update)
Calling
func (a adminapi) adminm2msetter(s toadminctx) toadminctx {
Pass in s.adminapi.update
as a parameter, the expected type is toadminctx
. Your type definition is:
type toadminctx func(ctx context.context, req interface{}) (interface{}, error)
But the second parameter of your update
function is *reqtype
, and its first return value is the resptype
value, so update
is not toadminctx
. toadminctx
A function type is a function that can be called using a context and literally any type . Your update
function is not guaranteed to work in all cases where the toadminctx
function does.
What you are looking for is a way to "wrap" any function, add some work on the ctx
parameters (maybe set some values), and then pass the call. Prior to go 1.19 we did this by adding some kind of wrapper type like this:
type wrapper struct { updatereqtype *reqtype anothertype *reqtype2 // for some other call you want to wrap }
Change all related functions, such as the update
function to take a wrapper parameter type:
func (a adminapi) update(ctx context.context, req wrapper) (resp, error) { realreq := req.updatereqtype // get the actual request used here }
Response types will be similarly wrapped and/or combined.
Now that go supports generics, they are very useful in this case, let's change the adminm2msetter
function to look like this:
func adminm2msetter[t any, r any](s func(context.context, t) (r, error)) func(context.context, t) (r, error) { return func (ctx context.context, arg t) (r, error) { m2mprincipal, _ := a.getm2mprincipal(ctx) ctxm2m := extlib.setprincipal(ctx, m2mprincipal) return s(ctxm2m, arg) } }
This way, we only need to define this function once, but rely on the compiler to generate a tailor-made function for all types we need. For the update
function, we do the following:
a.adminapi.adminm2msetter[*reqtype, resptype](s.adminapi.update)
Essentially replaces the generic t
and r
types with the specific types used by the update
function. Since I don't really know what function you are trying to wrap this way, I used t any, r any
, but since it seems to me that you are trying to wrap some kind of request handler, So you can create your own constraints:
type Requests interface { *ReqType1 | *ReqType2 | *ReqType3 // and so on } type Responses interface { Resp1 | Resp2 | Resp3 }
Just replace [t any, r any]
with [t requests, r responses]
The above is the detailed content of What parameters do Golang decorator functions have?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...
