Home  >  Article  >  Backend Development  >  How to assign a default fallback value to a variable

How to assign a default fallback value to a variable

WBOY
WBOYforward
2024-02-06 08:24:06547browse

How to assign a default fallback value to a variable

Question content

There is a struct pointer

in my application
type body struct {
   a *string
   b *string
}

I want to pass the values ​​of a and b in body to the function, so that if the pointer a is empty, the default is passed Empty string value. Something like this:

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

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

what should I do?


Correct answer


Declare a function for calculating a value from a pointer with your desired logic. I'm using generics here so the 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 usually provide helper functions for this purpose. For example, AWS API provides stringvalue function:

sampleFunc(ctx, aws.StringValue(A))

The above is the detailed content of How to assign a default fallback value to a variable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete