structure: add IsStruct() method

This commit is contained in:
Fatih Arslan 2014-07-27 14:48:26 +03:00
parent 0b38db7f76
commit 716932739a
3 changed files with 45 additions and 1 deletions

View File

@ -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")
}
```

View File

@ -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
}

View File

@ -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)
}
}