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

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

How to assign a default fallback value to a variable

问题

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

  1. type body struct {
  2. A *string
  3. B *string
  4. }

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

  1. sampleFunc(ctx,*A||"");
  2. func sampleFunc(ctx Context,count string){
  3. // ......
  4. }

我该如何做到这一点?

英文:

I have a struct of pointers in my app

  1. type body struct {
  2. A *string
  3. B *string
  4. }

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:

  1. sampleFunc(ctx,*A||"");
  2. func sampleFunc(ctx Context,count string){
  3. // ......
  4. }

How do I do this?

答案1

得分: 1

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

  1. count := ""
  2. if myBody.A != nil {
  3. count = *myBody.A
  4. }
  5. sampleFunc(ctx, count)

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

  1. func getOrDefault(val *string, deflt string) string {
  2. if val == nil {
  3. return deflt
  4. }
  5. return *val
  6. }
  7. count := getOrDefault(myBody.A, "")
  8. sampleFunc(ctx, count)
英文:

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

  1. count := ""
  2. if myBody.A != nil {
  3. count = *myBody.A
  4. }
  5. 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:

  1. func getOrDefault(val *string, deflt string) string {
  2. if val == nil {
  3. return deflt
  4. }
  5. return *val
  6. }
  7. count := getOrDefault(myBody.A, "")
  8. sampleFunc(ctx, count)

答案2

得分: 0

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

  1. // Value返回指针p指向的值,如果p为nil,则返回空值。
  2. func Value[T any](p *T) T {
  3. var result T
  4. if p != nil {
  5. result = *p
  6. }
  7. return result
  8. }

使用方法如下:

  1. sampleFunc(ctx, Value(A))

具有*string字段的API通常提供了用于此目的的辅助函数。例如,AWS API提供了StringValue函数:

  1. 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.

  1. // Value returns the value the value pointed
  2. // to by p or the empty value when p is nil.
  3. func Value[T any](p *T) T {
  4. var result T
  5. if p != nil {
  6. result = *p
  7. }
  8. return result
  9. }

Use like this:

  1. 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:

  1. 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:

确定