Home > Backend Development > Golang > How to Achieve Dynamic Type Return in Go?

How to Achieve Dynamic Type Return in Go?

Patricia Arquette
Release: 2024-12-02 05:33:14
Original
619 people have browsed it

How to Achieve Dynamic Type Return in Go?

How to Handle Dynamic Type Return in Golang?

Scenario:

In Golang Revel development, repetitive code arises due to similar data return types involving type struct. Consider the following functions:

func (c Helper) Brands() []*models.Brand {

    // Query rethinkdb and populate the Brand model
    var brands []*models.Brand
    rows.All(&brands)

    return brands

}

func (c Helper) BlogPosts() []*models.Post {

    // Query rethinkdb and populate the Post model
    var posts []*models.Post
    rows.All(&posts)

    return posts

}
Copy after login

In both cases, the return type is the same (*[]struct). To avoid duplication, a dynamic return type approach is proposed:

func (c Helper) ReturnModels(modelName string) []*interface{} {

    // Query rethinkdb with modelName and return []*interface{}
}
Copy after login

Questions:

  • Is dynamic type return possible?
  • How to implement it?

Answer:

Yes, dynamic type return is achievable. The function should return interface{} rather than []*interface{}. Here's how it can be implemented:

func (c Helper) ReturnModels(modelName string) interface{} {

    // Query rethinkdb with modelName and return interface{}
}
Copy after login

To utilize the returned value, type switches or type assertions are employed to cast it back to its original type:

Example:

if brands, ok := ReturnModels("brands").([]Brand); ok {
    // ...
}

if posts, ok := ReturnModels("posts").([]Post); ok {
    // ...
}
Copy after login

By implementing this approach, code duplication can be significantly reduced by using a single helper function for data retrieval.

The above is the detailed content of How to Achieve Dynamic Type Return in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template