How to add new methods to an existing type in Go?

前端 未结 2 1669
无人共我
无人共我 2020-12-07 07:25

I want to add a convenience util method on to gorilla/mux Route and Router types:

package util

import(
    \"net/http\"
    \"github.com/0xor1/         


        
2条回答
  •  失恋的感觉
    2020-12-07 08:04

    As the compiler mentions, you can't extend existing types in another package. You can define your own alias or sub-package as follows:

    type MyRouter mux.Router
    
    func (m *MyRouter) F() { ... }
    

    or by embedding the original router:

    type MyRouter struct {
        *mux.Router
    }
    
    func (m *MyRouter) F() { ... }
    
    ...
    r := &MyRouter{router}
    r.F()
    

提交回复
热议问题