0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Sai Krishna
  • 593
  • 1
  • 8
  • 25

2 Answers2

1

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)
LeGEC
  • 46,477
  • 5
  • 57
  • 104
0

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))