How do I find the type of an object in Go? In Python, I just use typeof
to fetch the type of object. Similarly in Go, is there a way to implement the same ?
Here is the container from which I am iterating:
for e := dlist.Front(); e != nil; e = e.Next() { lines := e.Value fmt.Printf(reflect.TypeOf(lines)) }
I am not able to get the type of the object lines in this case which is an array of strings.
The type keyword is there to create a new type. This is called type definition. The new type (in your case, Vertex) will have the same structure as the underlying type (the struct with X and Y). That line is basically saying "create a type called Vertex based on a struct of X int and Y int".
Interface Types: The interface is of two types one is static and another one is dynamic type. The static type is the interface itself, for example, tank in the below example. But interface does not have a static value so it always points to the dynamic values.
Using the New Keyword to Create Objects Another way to create an object from a struct is to use a new keyword. While using a new keyword, Golang creates a new object of the type struct and returns its memory location back to the variable. In short, the new keyword returns the address of the object.
Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.
The Go reflection package has methods for inspecting the type of variables.
The following snippet will print out the reflection type of a string, integer and float.
package main import ( "fmt" "reflect" ) func main() { tst := "string" tst2 := 10 tst3 := 1.2 fmt.Println(reflect.TypeOf(tst)) fmt.Println(reflect.TypeOf(tst2)) fmt.Println(reflect.TypeOf(tst3)) }
Output:
Hello, playground string int float64
see: http://play.golang.org/p/XQMcUVsOja to view it in action.
More documentation here: http://golang.org/pkg/reflect/#Type
I found 3 ways to return a variable's type at runtime:
Using string formatting
func typeof(v interface{}) string { return fmt.Sprintf("%T", v) }
Using reflect package
func typeof(v interface{}) string { return reflect.TypeOf(v).String() }
Using type assertions
func typeof(v interface{}) string { switch v.(type) { case int: return "int" case float64: return "float64" //... etc default: return "unknown" } }
Every method has a different best use case:
string formatting - short and low footprint (not necessary to import reflect package)
reflect package - when need more details about the type we have access to the full reflection capabilities
type assertions - allows grouping types, for example recognize all int32, int64, uint32, uint64 types as "int"
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