This question already has an answer here:
I want to write a function which takes two arguments interface{}
and a type and return true
if the interface is of the type passed, else return false
.
I am a beginner in reflection and main challenge I see is how to take type as a function parameter.
For example:
func checkType(val interface{}, t <??>){
if reflect.Typeof(val) == t {
return true
}else{
return false
}
}
checkType("hello",<int type>) // returns false
checkType("hello",<string type>) // returns true
I am not able to fill the code in all the <>
portions to achieve the required behavior.
Edit: Got queries about the safe type cast operator and also intent of my question. Though the methods suggested would help to achieve the type cast, the question was mainly to enhance the academic knowledge about Go reflection.
</div>
No need to write a function like this, it's already a built-in feature of the language:
i := "hello"
_, ok := i.(int) // ok is false
_, ok := i.(string) // ok is true