go - 没有实例的 TypeOf 并将结果传递给函数

标签 go reflection types

是否有可能在没有实例的情况下获得“类型”?我见过一些使用 reflect.TypeOf() 的示例,但它们都处理一个实例。

下面是我正在尝试做的事情的片段:

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 的方式?

最佳答案

是的,这是可能的。诀窍是从指向类型的指针开始(其值可以是 typed nil,完全没问题),然后使用 Type.Elem() 以获取指向类型(基本 类型)的 reflect.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)

输出(在 Go Playground 上尝试):

int
http.Request
os.File

查看相关问题:

Golang reflect: Get Type representation from name?

How to get the string representation of a type?

如果你想传递类型并在 switches 中使用它们,你可以像这样创建并存储它们一次到全局变量中,并引用全局变量:

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

上面的输出(在 Go Playground 上尝试):

Type: int
Type: http.request
Type: os.file
Type: uint64

但老实说,如果您以这种方式使用它并且您没有使用 reflect.Type 的方法,那么创建常量会更加容易和高效。它可能看起来像这样:

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

输出是一样的。在 Go Playground 上试用.

关于go - 没有实例的 TypeOf 并将结果传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48939416/

相关文章:

javascript - 模板文字类型等效

go - 使用 postgres 和 golang 准备语句

go - golang 中的 smtp 问题( panic ,信号 SIGSEGV : segmentation violation)

pointers - 创建变量会创建一个副本,取消引用不会。为什么?

go - 如何阅读 Go 文档?

c# - 有没有办法声明以任何 lambda 作为参数的方法?

java - 使 arrayList.toArray() 返回更具体的类型

java - 有没有更好(更安全)的方法来获取参数化类型的类?

typescript - 在类型中使用元组而不是联合数组

python - 如何检查实例化类属性类型?