Use reflection functions instead of switch syntax in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Recently in the company internship, participated in the company's Distributed Application Service system. The system adopts the Golang language as the development language of the system, and uses the feature of the reflex function of the go language in the development process to replace the previously used switch syntax.

Switch-case is a multi-choice grammar, and its essence is similar to the If-else method, which is to perform different methods by judging the conditions. And go provides a mechanism to update variables at run time and check their values, invoke their methods, and the intrinsic operations they support, but do not know the types of these variables at compile time. This mechanism is called reflection, and reflection allows us to treat the type itself as a value type of the first class.

Web Application Routing Issues

In the process of writing a Web application, we often encounter a route that requires a corresponding method, we will choose to use the switch method to do the matching of the route, if the route matches successfully, we will call a method, this method can be very simple to complete our work, It also makes it easy for programmers to clarify their ideas in the process of writing code.

Problem:

In the route of a URL, we use the cmd parameter in the request to correspond to a method, so how can we correspond to a method according to a CMD?

Probably for this question someone would say, why don't we put cmd in the URL, so that is a method corresponding to a route, and most of the web framework through the callback function to make function calls, in response to this problem, I can only say that most of it is to put the CMD in the HTTP request, the specific benefit may be to reduce the regulation of the API, and when the route more time to reduce the trouble it.

Use the switch method to achieve:

cmd := this.GetString("cmd")switch cmd{  case "ls":    ls()  case "cd":    cd()  default:    fmt.Println("cmd method missing")}

The above method first obtains the cmd through the URL parameter, then uses the CMD to call the corresponding method. In the traditional MVC design pattern, you need to add a switch method to the controller, and you need to implement the corresponding method in model, and modify 2 files in total.

Go Language Reflection function

Reflect Bag

In the reflect package, reflection is achieved mainly through the two methods of typeof () and valueof (). Two methods are combined to reflect all the information of the reflected function.

package mainimport (    "fmt"    "reflect")type Ref struct {       id int     name string}func (ref *Ref)GetName(){       fmt.Println("getName()函数")}func (ref *Ref)GetNameById(){    fmt.Println("getNameById()函数")}func main(){    t := reflect.TypeOf(&Ref{})    v := reflect.ValueOf(new(Ref))    fmt.Println(t)    fmt.Println(v)    for i:= 0; i< t.NumMethod();i++{        fmt.Println(t.Method(i).Name)        v.Method(i).Call(nil)    }}

TypeOf ()

The TypeOf () function mainly prints out the type of the reflected function, and the return result is reflect. Type.

In the above example, the method () is passed. Name can reflect the function name of its method.

Common methods:

    • Func (t *rtype) string () string
    • Func (t *rtype) Name () string
    • Func (t *rtype) Kind () Reflect.kind
    • Func (t *rtype) Method (int) reflect. Method
    • Func (t *rtype) Elem () reflect. Type
    • Func (t *rtype) in (int) reflect. Type

ValueOf ()

The ValueOf () function mainly prints out the type of the reflected function, and the return result is reflect. The value type.

In the above example, the method () is passed. Call () can reflect its function and execute it.

Common methods:

    • Func (v Value) string () string
    • Func (v Value) Elem () reflect. Value
    • Func (v Value) Method (int) reflect. Value
    • Func (v Value) call (in []value) (R []value)

The implementation process of reflection

Because of the presence of reflection, so in the traditional MVC design pattern, when we add the service, do not need to modify the controller side of the code, controller only need to maintain a map of the table, inside to store the need to be reflected models.

package server import(  "reflect"  "fmt")// ReServer 来保存map的结构体type ReServer struct {  m map[string]interface{}}// RegisterService 注册服务func (this *ReServer)RegisterService(service interface{})(err error){  serviceType := reflect.TypeOf(service).Elem()  ServiceName := serviceType.Name()  if _,ok := this.m[ServiceName]  if ok {    fmt.Println("service has been registered")  }else{    this.m[ServiceName] = service  }  return}//  Start 服务启动func (this *ReServer)Start(){  for k,v := range this.m {    // 里面根据业务逻辑执行想要的方法  }}

In the case of appeal, by registering services with service, you can discover the service through the start () function and implement your own code based on the business.

package mainimport (  "server")type Server struct {}func (server *Server)funOne(){  fmt.Println("Server FunOne")} func main(){  reServer := &server.ReServer{    m: make(map[string]interface{})  }  err := reServer.RegisterService(new(Server))  reServer.Start()}

So in our main function, we import encapsulated packages, just register a struct, and you can reflect your own method.

For the routing problem of the above web, we encapsulate the controller and then reflect the model, and when our business grows, we add it in the model, and we don't need to modify the controller.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.