Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - How can I check for type equality?

Tags:

go

Say I have the following code:

var x interface{}
y := 4
x = y
fmt.Println(reflect.TypeOf(x))

This will print int as the type. My question is how can I test for the type? I know there is the type switch which does this, so I could do:

switch x.(type) {
case int:
    fmt.Println("This is an int")
}

But if I only want to check for just one specific type the switch seems like the wrong tool. Is there a more direct method of doing this like

reflect.TypeOf(x) == int

or is the type switch the way to go?

like image 388
IamNaN Avatar asked Apr 04 '15 09:04

IamNaN


People also ask

How can you tell if two types are equal in TypeScript?

Use the strict equality operator (===) to check if two strings are equal in TypeScript, e.g. if (str1 === str2) {} . The strict equality operator returns true if the strings are equal, otherwise false is returned.

How can I check if two slices are equal to?

To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop. You can also use the reflect. DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level.

How do I compare types in TypeScript?

In Typescript, we have three ways to work with it using: typeof: the keyword helps to check values types, like boolean, string, number, etc. instanceof: the keyword to compare the object instance with a class constructor. type guards: The powerful way to check types using typescript feature language.


1 Answers

Type assertions return two values .. the first is the converted value, the second is a bool indicating if the type assertion worked properly.

So you could do this:

_, ok := x.(int)

if ok {
    fmt.Println("Its an int")
} else {
    fmt.Println("Its NOT an int")
}

..or, shorthand:

if _, ok := x.(int); ok {
    fmt.Println("Its an int")
}

See it in the playground

like image 126
Simon Whitehead Avatar answered Oct 12 '22 01:10

Simon Whitehead