Golang TypeOf没有实例并将结果传递给func

bgu*_*ura 2 reflection types go

是否可以在没有实例的情况下获得"类型"?我已经看到了一些使用的例子,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)) {
        // ....
    } / ....
}
Run Code Online (Sandbox Code Playgroud)

我的用法的一个例子是

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

注意,写这个出来之后,我知道我可以提供"RequireUint64","RequireUint32"等等.也许这将是围棋的方式?

icz*_*cza 9

是的,这是可能的.诀窍是从指向类型的指针开始(其值可以是类型 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)
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上试试):

int
http.Request
os.File
Run Code Online (Sandbox Code Playgroud)

查看相关问题:

Golang反映:从名称中获取类型表示?

如何获取类型的字符串表示?

如果你想传递类型并在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)
}
Run Code Online (Sandbox Code Playgroud)

以上输出(在Go Playground上试试):

Type: int
Type: http.request
Type: os.file
Type: uint64
Run Code Online (Sandbox Code Playgroud)

但老实说,如果你像这样使用它并且你没有使用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)
}
Run Code Online (Sandbox Code Playgroud)

输出是一样的.在Go Playground尝试一下.