Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check variable type at runtime in Go language

Tags:

go

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)?

like image 930
Darius Kucinskas Avatar asked Aug 09 '11 13:08

Darius Kucinskas


People also ask

Does Golang have type checking?

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.

What is type in GO Lang?

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.

Does Golang have type inference?

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.


1 Answers

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)))     }  } 
like image 66
Darius Kucinskas Avatar answered Sep 19 '22 19:09

Darius Kucinskas