Search code examples
gotiedot

ERROR: need type assertion


I thought I have asserted (as far as I've learnt Go), but I keep getting this error cannot use readBack["SomePIN"] (type interface {}) as type string in argument to c.String: need type assertion

Here is my code (this snippet is from a Request Handler function and I'm using Echo Web framework and Tiedot NoSQL database)

// To get query result document, simply 
// read it [as stated in the Tiedot readme.md]
for id := range queryResult {
    readBack, err := aCollection.Read(id)
    if err != nil {
        panic(err)
    }
    if readBack["OtherID"] == otherID {
        if _, ok := readBack["SomePIN"].(string); ok {
            return c.String(http.StatusOK, readBack["SomePIN"])
        }
    }
}

Solution

  • You are asserting readBack["SomePIN"] as a string - in the if statement. That doesn't make any change to readBack["SomePIN"], however - it's still an interface{}. In Go, nothing ever changes type. Here's what will work:

    for id := range queryResult {
        readBack, err := aCollection.Read(id)
        if err != nil {
            panic(err)
        }
        if readBack["OtherID"] == otherID {
            if somePIN, ok := readBack["SomePIN"].(string); ok {
                return c.String(http.StatusOK, somePIN)
            }
        }
    }
    

    You were tossing the string value from your type assertion, but you want it. So keep it, as somePIN, and then use it.

    Final note - using the value, ok = interfaceVal.(type) syntax is a good practice. If interfaceVal turns out to be a non-string, you'll get value = "" and ok = false. If you eliminate the ok value from the type assertion and interfaceVal is a non-string, the program will panic.