繁体   English   中英

我可以传递“类型”作为函数参数吗?

[英]Can I pass in a “Type” as a function parameter?

我正在尝试构建一个将结构类型自动用作RESTful资源的库。

这是我在调用代码中设想的样子:

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.")
}

在我的库中,我正在尝试创建Attach函数:

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
}

如何接受结构的任何“类型”? 我的最终目标是使用反射获取类型名称及其字段(这部分我已经知道了如何做)。

关于如何处理此问题的任何建议?

我发现的一种方法是:

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

然后,我可以使用任何想要的类型:

type Product struct {
    Name     string
    Quantity int
}

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

结果是:

/products
*main.Product

除非有更惯用的方式解决此问题,否则我认为我找到了解决方案。

您可能使用interface{}作为函数的参数类型。 然后,通过使用类型switch ,很容易知道参数的真实类型。

func MyFunc(param interface{}) {

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM