Table of Contents
Question content
Solution
Home Backend Development Golang What parameters do Golang decorator functions have?

What parameters do Golang decorator functions have?

Feb 08, 2024 pm 11:09 PM

Golang 装饰器函数的哪些参数

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) {}
Copy after login
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)
Copy after login

Solution

I think the error you are encountering is self-explanatory:

a.adminapi.adminm2msetter(s.adminapi.update)
Copy after login

Calling

func (a adminapi) adminm2msetter(s toadminctx) toadminctx {
Copy after login

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)
Copy after login

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
}
Copy after login

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
}
Copy after login

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)
    }
}
Copy after login

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)
Copy after login

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
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

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.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

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

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

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

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

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

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

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

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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,...

See all articles