Skip to content

Instantly share code, notes, and snippets.

@diabloneo
Last active March 25, 2021 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diabloneo/f607399581f8a7eea6ac3e1f596fa479 to your computer and use it in GitHub Desktop.
Save diabloneo/f607399581f8a7eea6ac3e1f596fa479 to your computer and use it in GitHub Desktop.
Fill a Golang struct's string fields' values according with fieldss names.
package common
import (
"fmt"
"go/token"
"reflect"
)
// FillStructString set values of string fields of a struct to the field names.
func FillStructString(value interface{}) {
v := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr {
panic("require a pointer")
}
v = v.Elem()
if v.Kind() != reflect.Struct {
panic("require pointer to a struct")
}
typ := v.Type()
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.Anonymous {
FillStructString(v.Field(i).Addr().Interface())
continue
}
if field.Type.Kind() != reflect.String {
continue
}
if !token.IsExported(field.Name) {
continue
}
v.Field(i).SetString(field.Name)
}
}
// CommonStatus are status shared by resources.
type CommonStatus struct {
Active string
Building string
BuildingError string
Deleting string
DeletingError string
Deleted string
}
// DataSourceStatusDefinition defines status.
type DataSourceStatusDefinition struct {
CommonStatus
Initializing string
}
// DataSourceStatus definitions.
var DataSourceStatus = new(DataSourceStatusDefinition)
func init() {
common.FillStructString(DataSourceStatus)
fmt.Printf("%+v\n", DataSourceStatus)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment