繁体   English   中英

map 中基于字符串键的 golang 开关类型

[英]golang switch type based on string key in map

我需要根据类型为 map 的字符串键获取类型。假设我有以下类型:

type RequestType struct {
  Type string `json:"type"`
  //Params map[string]string `json:"params"`//include params here? Contents of Params may be different among requests
}

type ParamsRequest struct {
 RequestType
 Param1 string
 Param2 string
}

type OtherRequest struct {
  RequestType
  Param3 string
  Param4 string
}

稍后的..

var requestTypes = map[string]protocol.RequestType{
  "base": ParamsRequest{}, //error here (Cannot use ParamsRequest as the type RequestType)
  "base2": OtherRequest{},
}

params := requestTypes["base"] //or base2

在代码中,我需要访问所有请求类型的公共字段:

myFunction(params.Type)//or params.Params 

或参数,特定于具体类型。 所以:

params := requestTypes["base"]
fmt.Println(params.Type)//common for everyone
fmt.Println(params.Param1)
fmt.Println(params.Param2)

或者:

params := requestTypes["base2"]
fmt.Println(params.Type)
fmt.Println(params.Param3)
fmt.Println(params.Param4)

或者:

params := requestTypes["base"]
fmt.Println(params.Params.Param1)
fmt.Println(params.Params.Param2)

但是当声明我的 map 时,我收到以下错误:

Cannot use ParamsRequest as the type RequestType

欢迎任何想法。 谢谢你。

如果我在这里正确理解了要求,那么您想创建一个interface of RequestType which will be implemented by both the Request structs 下面是它的示例代码。

package main

import "fmt"

type RequestType interface {
    Type() string // an interface with Type as a function
}
  
type ParamsRequest struct {
    Param1 string
    Param2 string
}
func (p ParamsRequest) Type() string { // different Type() logic for different Request types
    return fmt.Sprintf("%s,%s", p.Param1, p.Param2)
}
  
type OtherRequest struct {
    Param3 string
    Param4 string
}
func (o OtherRequest) Type() string {
    return fmt.Sprintf("%s,%s", o.Param3, o.Param4)
}

func main() {
    var requestTypes = map[string]RequestType{
        "base": ParamsRequest{Param1: "hi", Param2: "bye"}, //error here (Cannot use ParamsRequest as the type RequestType)
        "base2": OtherRequest{},
    }

    myFunction(requestTypes["base"].Type())
}

func myFunction(paramTypeString string) {
    fmt.Printf("%s\ndont know ...\n", paramTypeString)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM