structure: add IsStruct() method
This commit is contained in:
parent
0b38db7f76
commit
716932739a
22
README.md
22
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")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
11
structure.go
11
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
|
||||
}
|
||||
|
||||
@ -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)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user