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)?
The golang.org/x/tools/go/loader package from the x/tools repository is a client of the type checker that loads, parses, and type-checks a complete Go program from source code. We use it in some of our examples and you may find it useful too.
Type is the base interface for all data types in Go. This means that all other data types (such as int , float , or string ) implement the Type interface. Type is defined in the reflect header.
Go has various basic types(int8 , uint8 ( byte ), int16 , uint16 , int32 ( rune ), uint32) etc. Type constructors — Way for a programmer to define new types. Type Inference — The compiler can infer the type of a variable or a function without us having to explicitly specify it. Go has Uni-directional type inference.
It seems that Go have special form of switch dedicate to this (it is called type switch):
func (e *Easy)SetOption(option Option, param interface{}) { switch v := param.(type) { default: fmt.Printf("unexpected type %T", v) case uint64: e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v))) case string: e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v))) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With