简体   繁体   中英

cannot use true (type bool) as type string in function argument

I'm trying to get Search results from elastic search, but i'm getting this error:

cannot use true (type bool) as type string in function argument

Please can anyone can help to resolve it? I'm new to Go programming, so would appreciate suggestions to improve this case in the future.

This my code snippet

func SearchCallback(w *http.ResponseWriter, req *http.Request) {

    api.Domain = "127.0.0.1"

    // search males

    searchQuery := `{
        "query": {
            "term": {"content":"male"}
        }
    }`
    var response2 map[string]interface{}
    response2, err := core.SearchRequest(true, "people", "male", searchQuery, "")
    if err != nil {
        log.Fatalf("The search of males has failed:", err)
    }
    var values2 []interface{}
    for _, v := range response2.Hits.Hits {
        var value2 map[string]interface{}
        err := json.Unmarshal(v.Source, &value2)
        if err != nil {
            log.Fatalf("Failed to unmarshal, line 65", err)
        }
        values2 = append(values2, value2)
    }
    fmt.Println(values2)

    jsonV2, err := json.Marshal(values2)
    if err != nil {
        log.Fatalf("Failed marshalling: line 71", err)
    }
    fmt.Println(string(jsonV2))
}

Go doesn't have implicit type conversion. Since you're new to programming -- what this amounts to is saying that one type cannot be treated as another without explicitly stating that you want it to be treated as such. An int is not a float, a float is not a slice, and a bool is not a string. Sometimes you can use type conversions to fix this, unfortunately, for boolean values you cannot simply use a type conversion. That is, string(bool) will not compile.

There are multiple ways to fix this. One is to replace true with fmt.Sprintf("%t",true) . This is the more general case, if true was instead a boolean variable it would return a string that says "true" or "false" depending. It also generalizes well to other types such as integers, fmt.Sprintf("%d",myInteger) , for instance, would convert an int to a string .

However... in this case since the value is always true, it's needless, just replace true with "true" . The string that "%t" will return will be the string "true" so there's no need to go through the conversion hassle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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