Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

arrays - Print Missing Values

Using Go, I am trying to send values from main to the function. I want to check if any parameter sent to function is empty. If there is any missing values, I want to print that the "Parameter value" is empty. If there are multiple parameters empty, I want to print that as well. If all parameters are correctly given, return the value.

func FederationValidarator(a string, b string) (string, string) {
    // var Messages []string
    rArray := [2]string{a, b}
    // i :=0
    for i := 0; i < len(rArray); i++ {
        if rArray[i] != "" {
            fmt.Println("Nothing is empty")
        } else {
            // var Messages []string
            fmt.Println("%s is Missing")
        }
    }
    return a, b
}

func main() {
    a, b := FederationValidarator("", "world")
    fmt.Println(a)
    fmt.Println(b)
}

How can i code to print missing values? I want to get the following output.

The results:

%s is Missing
Nothing is empty

world

Expected Output:

a is Missing
world
question from:https://stackoverflow.com/questions/65623325/print-missing-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...