英文:
How to assign a default fallback value to a variable
问题
我在我的应用程序中有一个指针的结构体。
type body struct {
A *string
B *string
}
我想将body
中A
和B
的值传递给函数,如果指针A
为空,则传递一个默认的空字符串值。类似于:
sampleFunc(ctx,*A||"");
func sampleFunc(ctx Context,count string){
// ......
}
我该如何做到这一点?
英文:
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?
答案1
得分: 1
没有为此提供内置的语法糖,只需编写以下代码:
count := ""
if myBody.A != nil {
count = *myBody.A
}
sampleFunc(ctx, count)
如果你发现自己经常写这段代码(比如:对于许多不同的字段),你可以创建一个辅助函数,例如:
func getOrDefault(val *string, deflt string) string {
if val == nil {
return deflt
}
return *val
}
count := getOrDefault(myBody.A, "")
sampleFunc(ctx, count)
英文:
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)
答案2
得分: 0
声明一个函数,其中包含计算指针值的所需逻辑。我在这里使用了泛型,所以该函数适用于任何类型。
// Value返回指针p指向的值,如果p为nil,则返回空值。
func Value[T any](p *T) T {
var result T
if p != nil {
result = *p
}
return result
}
使用方法如下:
sampleFunc(ctx, Value(A))
具有*string
字段的API通常提供了用于此目的的辅助函数。例如,AWS API提供了StringValue函数:
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.
// 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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论