首页 > 解决方案 > 根据 switch 语句更改变量类型

问题描述

我正在 Go 中创建一个 POST HTTP 请求函数,该函数将通过参数接受不同的数据类型,但是在将 switch 语句中的值分配给 requestData 变量时我被卡住了。

理想情况下,requestData 将是 nil 类型,直到我们转到 switch 语句然后为其分配值和类型。任何帮助表示赞赏:)

requestData 上的错误消息:“语法错误:意外类型,预期类型”

我的代码:

main() {
    ..

    // CASE 1: we are passing the form of url.Values type
    form := url.Values{}
    form.Add("note", "john2424")
    form.Add("http", "clear")

    response := POST("www.google.co.uk", client, form) // first POST request



    // CASE 2: we are passing the JSON data using []byte type
    jsonData := []byte(`{"ids":[12345]}`)
    response := POST("www.google.co.uk", client, jsonData) // second POST request
}

func POST(website string, client *http.Client, data interface{}) (bodyString string) {
    var requestData type // <<<<<<< Change requestData to a variable from switch case 

    switch data.(type) { // switch case based on type 
    case url.Values: // URL form data
        formattedData := data.(url.Values) // convert interface to url.Values
        requestData := strings.NewReader(formattedData.Encode()) // *Reader type
    case []byte: // JSON
        formattedData := data.([]byte) // convert interface to []byte
        requestData := bytes.NewBuffer(formattedData) // *Buffer type
    default: // anything else

    }

    request, err := http.NewRequest("POST", website, requestData)
    if err != nil {
        log.Fatal(err)
    }


    response, err := client.Do(request)
    if err != nil {
        log.Fatal(err)
    }

    defer response.Body.Close()
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    } else {
        bodyString = string(body)
    }

    return
}

标签: variablesgointerfaceswitch-statement

解决方案


将输入的数据输入开关

typedData:=switch data.(type) {

然后用它来转换例如

case []byte: // JSON
        requestData := bytes.NewBuffer(typedData) // *Buffer type

尽管@mkopriva 的游乐场示例看起来是一个更好的主意


推荐阅读