From 716932739aa1d445147d8a0513ea71d652ba77d6 Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Sun, 27 Jul 2014 14:48:26 +0300 Subject: [PATCH] structure: add IsStruct() method --- README.md | 22 +++++++++++++++++++++- structure.go | 11 +++++++++++ structure_test.go | 13 +++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fc81f67..df3a5f6 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Structure contains various utilitis to work with Go (Golang) structs. go get github.com/fatih/structure ``` -## Example +## Examples Below is an example which converts a **struct** to a **map** ```go @@ -32,4 +32,24 @@ if err != nil { fmt.Printf("%#v", m) // Output: map[string]interface {}{"Name":"Arslan", "ID":123456, "Enabled":true} ``` + +Test if the given variable is a struct or not + +```go +type Server struct { + Name string + ID int32 + Enabled bool +} + +s := &Server{ + Name: "Arslan", + ID: 123456, + Enabled: true, +} + +if structure.IsStruct(s) { + fmt.Println("s is a struct") +} +``` diff --git a/structure.go b/structure.go index 2fcf7fa..b389fc7 100644 --- a/structure.go +++ b/structure.go @@ -49,3 +49,14 @@ func ToMap(in interface{}) (map[string]interface{}, error) { return out, nil } + +// IsStruct returns true if the given variable is a struct or a pointer to +// struct. +func IsStruct(strct interface{}) bool { + t := reflect.TypeOf(strct) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + + return t.Kind() == reflect.Struct +} diff --git a/structure_test.go b/structure_test.go index 057d0e0..5cacc67 100644 --- a/structure_test.go +++ b/structure_test.go @@ -92,3 +92,16 @@ func TestToMap_Tag(t *testing.T) { } } + +func TestStruct(t *testing.T) { + var T = struct{}{} + + if !IsStruct(T) { + t.Errorf("T should be a struct, got: %T", T) + } + + if !IsStruct(&T) { + t.Errorf("T should be a struct, got: %T", T) + } + +}