
我的应用程序中有一个 struct 指针
type body struct {
a *string
b *string
}
我想将body中的a和b的值传递给函数,这样如果指针a为空,则传递默认的空字符串值。像这样的东西:
sampleFunc(ctx,*A||"");
func sampleFunc(ctx Context,count string){
// ......
}我该怎么做?
使用您所需的逻辑声明一个函数,用于从指针计算值。我在这里使用泛型,因此函数适用于任何类型。
// value returns the value the value pointed
// to by p or the empty value when p is nil.
func value[t any](p *t) t {
var result t
if p != nil {
result = *p
}
return result
}像这样使用:
samplefunc(ctx, value(a))
带有 *string 字段的 api 通常会为此目的提供辅助函数。例如,aws api 提供 stringvalue函数:
sampleFunc(ctx, aws.StringValue(A))
以上就是如何为变量分配默认回退值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号