在Go语言中,可以使用if语句结合ok断言来判断一个map中是否包含指定的key,并且该key对应的valuestring类型且值不为空。

以下是一个示例代码:

package main

import (
	"fmt"
)

func main() {
	m := map[string]interface{}{
		"key1": "value1",
		"key2": "value2",
		"key3": 123,
	}

	key := "key1"

	if val, ok := m[key]; ok {
		if strVal, ok := val.(string); ok && strVal != "" {
			fmt.Printf("The map contains the key '%s' with a non-empty string value: %s\n", key, strVal)
		} else {
			fmt.Printf("The map contains the key '%s', but the value is either not a string or empty\n", key)
		}
	} else {
		fmt.Printf("The map does not contain the key '%s'\n", key)
	}
}

在上述示例中,我们首先使用ok断言来判断key是否存在于map中。如果存在,则继续进行第二个if语句的判断。在第二个if语句中,我们使用ok断言来判断value是否为string类型,并且通过strVal != ""的条件判断value是否为空字符串。如果满足这两个条件,则表示map中包含指定的keyvalue是非空字符串。否则,表示要么value不是string类型,要么是空字符串。

golang if 判断map 中是否包含指定的key 并且value是string 并且值不能为空

原文地址: https://www.cveoy.top/t/topic/hLsg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录