没有实例并将结果传递给func的TypeOf [英] TypeOf without an instance and passing result to a func
问题描述
是否可以在没有实例的情况下获取类型"?我看过一些利用 reflect.TypeOf()
的示例,但是它们都处理一个实例.
Is it possible in go to get a "Type" without an instance? I've seen some examples that utilize reflect.TypeOf()
but they all deal with an instance.
下面是我正在尝试做的一小段:
Below is a snippet of what I am attempting to do:
import (
"net/http"
)
type ParamReader struct {
// The request from which to extract parameters
context *http.Request
}
// Initialize the ParamReader with a specific http request. This serves
// as the 'context' of our param reader. All subsequent calls will validate
// the params that are present on this assigned http.Request
func (p *ParamReader) Context(r *http.Request) {
p.context = r
}
// Validate that a given param 's' is both present and a valid
// value of type 't'. A value is demeed valid if a conversion from
// its string representation to 't' is possible
func(p *ParamReader) Require(s string, t Type) {
// if context not have 's'
// addError('s' is not present)
// return
if( t == typeof(uint64)) {
// If not s -> uint64
// addError('s' is not a valid uint64)
} else if (t == typeof(uint32)) {
// ....
} / ....
}
我的用法示例是
func (h *Handler) OnRequest(r *http.Request) {
h.ParamReader.Context(r)
h.ParamReader.Require("age", uint16)
h.ParamReader.Require("name", string)
h.ParamReader.Require("coolfactor", uint64)
h.ParamReader.Optional("email", string, "unspecified")
h.ParamReader.Optional("money", uint64, "0")
if h.ParamReader.HasErrors() {
// Iterate or do something about the errors
} else {
coolness := h.ParamReader.ReadUint64("coolfactor")
email := h.ParamReader.ReadString("email")
money := h.ParamReader.ReadUint64(0)
}
}
注意,在写完这些之后,我意识到我可以提供"RequireUint64"
,"RequireUint32"
等.也许这就是Go的方式吗?
Note, after writing this out, I realize I could provide a "RequireUint64"
, "RequireUint32"
, etc.. perhaps that would be the Go way?
推荐答案
是的,有可能.诀窍是从指向类型的指针开始(其值可以是 typed nil
,这完全可以),然后使用 Type.Elem()
以获得指向类型( base 类型)的 reflect.Type
描述符.
Yes, it's possible. The trick is to start from a pointer to the type (whose value can be a typed nil
, that's perfectly OK), and then use Type.Elem()
to get the reflect.Type
descriptor of the pointed type (the base type).
查看一些示例:
t := reflect.TypeOf((*int)(nil)).Elem()
fmt.Println(t)
t = reflect.TypeOf((*http.Request)(nil)).Elem()
fmt.Println(t)
t = reflect.TypeOf((*os.File)(nil)).Elem()
fmt.Println(t)
输出(在转到游乐场上尝试):
int
http.Request
os.File
查看相关问题:
如果要传递类型并在 switch
es中使用它们,可以像这样一次创建并存储在全局变量中,并引用全局变量:
If you want to pass around the types and use them in switch
es, you can create and store them in global variables once like this, and refer to the global vars:
var (
intType = reflect.TypeOf((*int)(nil))
httpRequestType = reflect.TypeOf((*http.Request)(nil))
osFileType = reflect.TypeOf((*os.File)(nil))
int64Type = reflect.TypeOf((*uint64)(nil))
)
func printType(t reflect.Type) {
switch t {
case intType:
fmt.Println("Type: int")
case httpRequestType:
fmt.Println("Type: http.request")
case osFileType:
fmt.Println("Type: os.file")
case int64Type:
fmt.Println("Type: uint64")
default:
fmt.Println("Type: Other")
}
}
func main() {
printType(intType)
printType(httpRequestType)
printType(osFileType)
printType(int64Type)
}
上述内容的输出(在转到游乐场上尝试)
Output of the above (try it on the Go Playground):
Type: int
Type: http.request
Type: os.file
Type: uint64
但是,老实说,如果您以这种方式使用它,并且没有使用 reflect.Type
的方法,那么创建常量将变得更加容易和高效.看起来可能像这样:
But honestly, if you're using it like this way and you're not using reflect.Type
's methods, then creating constants is much easier and more efficient. It could look like this:
type TypeDesc int
const (
typeInt TypeDesc = iota
typeHttpRequest
typeOsFile
typeInt64
)
func printType(t TypeDesc) {
switch t {
case typeInt:
fmt.Println("Type: int")
case typeHttpRequest:
fmt.Println("Type: http.request")
case typeOsFile:
fmt.Println("Type: os.file")
case typeInt64:
fmt.Println("Type: uint64")
default:
fmt.Println("Type: Other")
}
}
func main() {
printType(typeInt)
printType(typeHttpRequest)
printType(typeOsFile)
printType(typeInt64)
}
输出是相同的.在去游乐场上尝试.
Output is the same. Try it on the Go Playground.
这篇关于没有实例并将结果传递给func的TypeOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!