snippetgoModerate
How to check variable type at runtime in Go language?
Viewed 0 times
howcheckruntimelanguagevariabletype
Problem
I have a few C functions declared like this:
I would like to expose those as one Go function like this:
So I need to be able to check
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.
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...
}Code Snippets
func (e *Easy)SetOption(option Option, param interface{}) {
if s, ok := param.(string); ok {
// s is string here
}
// else...
}Context
Stack Overflow Q#6996704, score: 37
Revisions (0)
No revisions yet.