Home > Article > Backend Development > How to assign a default fallback value to a variable
There is a struct
pointer
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?
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!