How to check variable type at runtime in Go language

Issue

I have 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 good idea (if not what is 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) {
        // s is string here
    }
    // else...
}

Answered By – Deleted

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.