Home >Backend Development >Golang >How Can I Add Methods to Existing Types in Go?

How Can I Add Methods to Existing Types in Go?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 10:07:39767browse

How Can I Add Methods to Existing Types in Go?

Extending Existing Types in Go

When attempting to add custom methods to existing types from imported packages, you may encounter an error indicating that you cannot define new methods on non-local types. This limitation stems from Go's type system, which disallows modifications to types defined elsewhere.

To circumvent this restriction, there are two primary approaches:

  1. Define a New Type with Anonymous Fields: This involves creating a new type that embeds the original type as anonymous fields. You can then add custom methods to your new type.
type MyRoute struct {
    *mux.Route
}

func (m *MyRoute) Subroute(tpl string, h http.Handler) *mux.Route {
    return m.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}

type MyRouter struct {
    *mux.Router
}

func (r *MyRouter) Subroute(tpl string, h http.Handler) *mux.Route {
    return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}
  1. Embed the Existing Type: Instead of anonymous embedding, you can explicitly embed the existing type using the embed keyword. This provides access to the fields and methods of the original type while allowing you to define additional methods.
type MyRoute embed mux.Route

func (m *MyRoute) Subroute(tpl string, h http.Handler) *mux.Route {
    return m.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}

type MyRouter embed mux.Router

func (r *MyRouter) Subroute(tpl string, h http.Handler) *mux.Route {
    return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}

The above is the detailed content of How Can I Add Methods to Existing Types in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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