gotypesreflection

How to check variable type at runtime in Go language?


I have a few C functions declared like this:

CURLcode curl_wrapper_easy_setopt_long(CURL* curl, CURLoption option, long param);
CURLcode curl_wrapper_easy_setopt_str(CURL* curl, CURLoption option, char* param);

I would like to expose those as one Go function like this:

func (e *Easy)SetOption(option Option, param interface{})

So I need to be able to check param type at runtime. How do I do that and is this a good idea (if not what is a good practice in this case)?


Solution

  • See type assertions here:

    http://golang.org/ref/spec#Type_assertions

    I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.

    func (e *Easy)SetOption(option Option, param interface{}) {
        if s, ok := param.(string); ok {
            // s is string here
        }
        // else...
    }