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

huangapple go评论66阅读模式
英文:

How to assign a default fallback value to a variable

问题

我在我的应用程序中有一个指针的结构体。

type body struct {
   A *string
   B *string
}

我想将bodyAB的值传递给函数,如果指针A为空,则传递一个默认的空字符串值。类似于:

sampleFunc(ctx,*A||"");

func sampleFunc(ctx Context,count string){
// ......
}

我该如何做到这一点?

英文:

I have a struct of pointers in my app

type body struct {
   A *string
   B *string
}

I want to pass the values of A and B in the body to function, such that if the pointer A is null, pass a default empty string value. Something like:

sampleFunc(ctx,*A||"");

func sampleFunc(ctx Context,count string){
// ......
}

How do I do this?

答案1

得分: 1

没有为此提供内置的语法糖,只需编写以下代码:

count := ""
if myBody.A != nil {
    count = *myBody.A
}

sampleFunc(ctx, count)

如果你发现自己经常写这段代码(比如:对于许多不同的字段),你可以创建一个辅助函数,例如:

func getOrDefault(val *string, deflt string) string  {
    if val == nil {
        return deflt
    }
    return *val
}

count := getOrDefault(myBody.A, "")
sampleFunc(ctx, count)
英文:

There is no built-in syntactic sugar for that, just write the code:

count := ""
if myBody.A != nil {
    count = *myBody.A
}

sampleFunc(ctx, count)

If you find yourself writing this block of code often (say: for many separate fields), you can for example create a helper function:

func getOrDefault(val *string, deflt string) string  {
    if val == nil {
        return deflt
    }
    return *val
}


count := getOrDefault(myBody.A, "")
sampleFunc(ctx, count)

答案2

得分: 0

声明一个函数,其中包含计算指针值的所需逻辑。我在这里使用了泛型,所以该函数适用于任何类型。

// Value返回指针p指向的值,如果p为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))
英文:

Declare a function with your desired logic for computing a value from the pointer. I use generics here so function works with any type.

// 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
}

Use like this:

sampleFunc(ctx, Value(A))

APIs with *string fields often provide a helper function for this purpose. For example, the AWS API provides the StringValue function:

sampleFunc(ctx, aws.StringValue(A))

huangapple
  • 本文由 发表于 2023年5月12日 07:06:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76232139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定