首页  >  文章  >  后端开发  >  如何为变量分配默认回退值

如何为变量分配默认回退值

WBOY
WBOY转载
2024-02-06 08:24:06485浏览

如何为变量分配默认回退值

问题内容

我的应用程序中有一个 struct 指针

type body struct {
   a *string
   b *string
}

我想将body中的ab的值传递给函数,这样如果指针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中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除