Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add typed API to pkg/attribute #2486

Merged
merged 1 commit into from
Jun 18, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions pkg/attribute/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,61 @@ type Description struct {
Checker func(i interface{}) error
}

// Int declares an attribute of int-typed in Dictionary d.
func (d Dictionary) Int(name string, value int, doc string, checker func(int) error) Dictionary {
d[name] = &Description{
Type: Int,
Default: value,
Doc: doc,
Checker: func(x interface{}) error { return checker(x.(int)) },
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I should make it

func(x interface{}) error {
    v, ok := x(int)
    if ! ok {
         return fmt.Errorf("Attribute %s is of type int, but the value %v cannot be casted into int", name, x)
    }
    return checker(v)
}

}
return d
}

// Float declares an attribute of float32-typed in Dictionary d.
func (d Dictionary) Float(name string, value float32, doc string, checker func(float32) error) Dictionary {
d[name] = &Description{
Type: Float,
Default: value,
Doc: doc,
Checker: func(x interface{}) error { return checker(x.(float32)) },
}
return d
}

// Bool declares an attribute of bool-typed in Dictionary d.
func (d Dictionary) Bool(name string, value bool, doc string, checker func(bool) error) Dictionary {
d[name] = &Description{
Type: Bool,
Default: value,
Doc: doc,
Checker: func(x interface{}) error { return checker(x.(bool)) },
}
return d
}

// String declares an attribute of string-typed in Dictionary d.
func (d Dictionary) String(name string, value string, doc string, checker func(string) error) Dictionary {
d[name] = &Description{
Type: String,
Default: value,
Doc: doc,
Checker: func(x interface{}) error { return checker(x.(string)) },
}
return d
}

// IntList declares an attribute of []int-typed in Dictionary d.
func (d Dictionary) IntList(name string, value []int, doc string, checker func([]int) error) Dictionary {
d[name] = &Description{
Type: IntList,
Default: value,
Doc: doc,
Checker: func(x interface{}) error { return checker(x.([]int)) },
}
return d
}

// FillDefaults fills default values defined in Dictionary to attrs.
func (d Dictionary) FillDefaults(attrs map[string]interface{}) {
for k, v := range d {
Expand Down