You can't get the parameter names (e.g. a
), for details, see Getting method parameter names.
If you need the parameter names, wrap the parameters into a struct, and you can get the names of the fields. You may use reflection to iterate over the fields, and get their values and their names too.
For example:
type Param struct {
A string
B string
C string
}
func CheckValues(p Param) {
v := reflect.ValueOf(p)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
name := t.Field(i).Name
if v.Field(i).IsZero() {
fmt.Printf("%s is empty
", name)
} else {
fmt.Printf("%s is NOT empty
", name)
}
}
}
Testing it:
p := Param{"", "world", ""}
CheckValues(p)
Output (try it on the Go Playground):
A is empty
B is NOT empty
C is empty
One very nice property of this solution is that it does not depend on the actual parameter type. You may pass any struct values to it, and it will continue to work. Also it handles "all" field types, not just strings.
So modify the signature to this:
func CheckValues(p interface{})
And you may also pass anonymous structs, not just values of defined types:
a, b, c, d := "", "world", 0, 3
CheckValues(struct {
A string
B string
C int
D int
}{a, b, c, d})
This will output (try it on the Go Playground):
A is empty
B is NOT empty
C is empty
D is NOT empty