2014-05-20 106 views
0

我试图建立一个库,它将自动将一个struct Type作为一个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.") 
} 

在我的图书馆,我试图创建附加功能:

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 
} 

如何我可以接受任何“类型”的结构?我的最终目标是使用反射来获取类型名称和它的字段(这一部分我已经知道该怎么做)。

关于如何解决这个问题的任何建议?

+0

我做了类似的地方,我的函数接受'reflect.Type',当我调用它时,它看起来像'attach(reflect.TypeOf(MyStruct {}))''。但是你不能通过接口解决它吗? –

+0

你可以使用一个'interface {}'然后一个类型开关。 http://golang.org/doc/effective_go.html#type_switch – julienc

+0

@Kbo:事情是我不知道将会有什么类型。这些应该在运行时检测到。 – sergserg

回答

1

我发现了一个办法是:

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 

除非有更习惯的方式去做这件事,我想我找到了我的解决方案。

+0

正如上面已经提到的,只是使用一个接口来传递产品而不是所有的花哨东西。这是我认为这样做的惯用方式。也许界面可能有一个返回到产品类型的函数:GetProductType()Reflect.Type(不知道会做什么) – gigatropolis

0

您可以使用interface{}作为函数的参数类型。然后,通过使用type switch知道实际参数的类型将是相当容易的。

func MyFunc(param interface{}) { 

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

事情是我不知道什么类型将在手前。这些应该在运行时检测到。 – sergserg

+0

运行时的事件,这些类型必须已经在代码中的某处定义。在这种类型的开关中列出所有允许的类型是不是可能的? – julienc

+0

除非您想将您的代码用作其他项目的外部包,并且仍然能够使用它们中定义的特定类型? – julienc

相关问题