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

How to assign a default fallback value to a variable

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-06 08:24:06
forward
665 people have browsed it

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
}
Copy after login

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){
// ......
}
Copy after login

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
}
Copy after login

Use like this:

samplefunc(ctx, value(a))
Copy after login

APIs with *string fields usually provide helper functions for this purpose. For example, AWS API provides stringvalue function:

sampleFunc(ctx, aws.StringValue(A))
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template