sergserg
sergserg

Reputation: 22224

Can I pass in a "Type" as a function parameter?

I'm trying to build a library that'll serve a struct Type as a RESTful resource automatically.

Here's what I envision it to look like in the calling code:

package main

import (
    "fmt"
    "github.com/sergiotapia/paprika"
)

type Product struct {
    Name     string
    Quantity int
}

func main() {
    // You need to attach a resource by giving Paprika your route,
    // the struct type and optionally a custom resource manager.
    paprika.Attach("/products", Product, nil)
    paprika.Start(1337)
    log.Print("Paprika is up and running.")
}

Inside of my library, I'm trying to create the Attach function:

package paprika

import (
    "fmt"
)

func Attach(route string, resource Type, manager ResourceManager) {

}

func Start(port int) {

}

type ResourceManager interface {
    add() error
    delete() error
    update(id int) error
    show(id int) error
    list() error
}

How can I accept any "Type" of struct? My end goal is to use reflection to get the type name and it's fields (this part I already know how to do).

Any suggestions on how to approach this?

Upvotes: 0

Views: 93

Answers (2)

sergserg
sergserg

Reputation: 22224

An approach I found is:

func Attach(route string, resource interface{}) {
    fmt.Println(route)
    fmt.Println(reflect.TypeOf(resource))
}

Then I can use any type I want:

type Product struct {
    Name     string
    Quantity int
}

func main() {
    Attach("/products", new(Product))
}

Results in:

/products
*main.Product

Unless there's a more idiomatic way to go about this, I think I found my solution.

Upvotes: 1

julienc
julienc

Reputation: 20305

You could probably use an interface{} as parameter type for your function. Then, it would be quite easy to know the real type of your parameter by using a type switch.

func MyFunc(param interface{}) {

    switch param.(type) {
        case Product:
            DoSomething()
        case int64:
            DoSomethingElse()
        case []uint:
            AnotherThing()
        default:
            fmt.Println("Unsuported type!")
    }
}

Upvotes: 0

Related Questions