
php小编子墨在这里为大家解答一个关于Sprintf函数的问题。有时候我们需要使用Sprintf函数来格式化字符串,但是在某些情况下,我们可能会遇到具有三种不同指针类型的参数的情况,而且这些参数可能为nil。在这种情况下,我们无法使用三元运算符来处理,否则代码会变得冗长而且不易阅读。那么,我们应该如何避免写几十行的冗长代码呢?接下来,我将为大家分享一种简洁的解决方案。
问题内容
我要使用 sprintf 创建此字符串
message := fmt.sprintf("unit %s has a level of %v, but is of category %v",
*entity.name, *entity.levelcode, *entity.categorycode)
在实体中,变量是指针,可以是nil:
-
name是*string -
levelcode具有*levelcode类型 -
categorycode具有*categorycode类型
但如果它们有一个值,我想要这个值而不是指针。 (即单元 abc 的级别为零,但属于管理单元类别)
无论用什么语言,我都会这样写:
message := fmt.sprintf("unit %s has a level of %v, but is of %v category",
entity.name != nil ? *entity.name : "nil", entity.levelcode != nil ? *entity.levelcode : "nil", entity.categorycode != nil ? *entity.categorycode : "nil")
但是go不允许三元运算符。如果我不处理 nil 值,sprintf 将抛出异常。
那么,我必须这样开始吗?
if entity.Name == nil && entity.LevelCode != nil && entity.CategoryCode != nil) {
message := "Unit nil has a Level of nil, but is of nil Category"
}
else {
if entity.Name != nil && entity.LevelCode != nil && entity.CategoryCode != nil) {
message := fmt.Sprintf("Unit %s has a Level of nil, but is of nil Category",
entity.Name != nil ? *entity.Name : "nil")
}
else {
...
for 9 combinations of values nil or not nil values, and 9 sprintf formats?
}
}
What the shortest way to dump my variables content in a formatted line?
解决方法
谢谢,在你的帮助下,我成功地构建了该函数。
// value treat pointers that can be nil, and return their values if they aren't.
func value[t any](v *t) string {
if (v != nil) {
return fmt.sprintf("%v", *v)
} else {
return "nil"
}
}
这样称呼
message := fmt.Sprintf("Unit %s has a Level of %v, but is of %v Category",
value(entity.Name), value(entity.LevelCode), value(entity.CategoryCode))
为单个 sprintf 编写五个语句...但它有效。










