2014-05-20 110 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

相關問題