打印缺失值

使用Go,我正在尝试将值从main发送到函数。我想检查发送到函数的任何参数是否为空。如果有任何缺失值,我想打印“参数值”为空。如果有多个参数为空,我也想打印出来。如果正确给出了所有参数,则返回该值。


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)

}

如何编码以打印缺失值?我想得到以下输出。


结果:


%s is Missing

Nothing is empty


world

预期输出:


a is Missing

world


梦里花落0921
浏览 113回答 2
2回答

繁星coding

无法获取参数名称(例如 ),有关详细信息,请参阅获取方法参数名称。a如果需要参数名称,请将参数包装到结构中,即可获取字段的名称。您可以使用反射来循环访问字段,并获取其值和名称。例如:type Param struct {&nbsp; &nbsp; A string&nbsp; &nbsp; B string&nbsp; &nbsp; C string}func CheckValues(p Param) {&nbsp; &nbsp; v := reflect.ValueOf(p)&nbsp; &nbsp; t := v.Type()&nbsp; &nbsp; for i := 0; i < v.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; name := t.Field(i).Name&nbsp; &nbsp; &nbsp; &nbsp; if v.Field(i).IsZero() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s is empty\n", name)&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s is NOT empty\n", name)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}测试它:p := Param{"", "world", ""}CheckValues(p)输出(在Go Playground上尝试):A is emptyB is NOT emptyC is empty此解决方案的一个非常好的属性是它不依赖于实际的参数类型。您可以将任何结构值传递给它,它将继续工作。此外,它还处理“所有”字段类型,而不仅仅是字符串。因此,将签名修改为:func CheckValues(p interface{})您还可以传递匿名结构,而不仅仅是定义类型的值:a, b, c, d := "", "world", 0, 3CheckValues(struct {&nbsp; &nbsp; A string&nbsp; &nbsp; B string&nbsp; &nbsp; C int&nbsp; &nbsp; D int}{a, b, c, d})这将输出(在Go Playground上尝试):A is emptyB is NOT emptyC is emptyD is NOT empty

慕姐4208626

此代码是为了匹配您期望的结果。但这不是检查参数名称的正确方法。func FederationValidarator(a string, b string) (string, string) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; rArray := [2]string{a, b}&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for i := 0; i < len(rArray); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if string(rArray[i]) == "" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s is Missing\n", rArray[i]) // %s is empty string, Then nothing will appear.&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println(rArray[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return a, b}&nbsp;func main() {&nbsp; &nbsp; _, _ = FederationValidarator("", "world")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go