Reputation: 2408
Hi I want to log the value of a variable if it is not nil otherwise I want to print anything else
for example:
var point *string
var point2 *string
p:="hi"
point2=&p
fmt.Printf("%v,%v",*point,*point2)
in this case I will have an error since point is nill, so is there any way to print the value of the variable if it is not nil or print anything else if it is nil?
I want to do this in a simple way instead of creating an if/else statement to check if the variable is nil
Upvotes: 9
Views: 6301
Reputation: 2679
I can recommend using https://github.com/samber/lo
Among other useful functions there is FromPtrOr
:
str := "hello world"
value := lo.FromPtrOr(&str, "empty")
// "hello world"
value := lo.FromPtrOr[string](nil, "empty")
// "empty"
Upvotes: 1
Reputation: 4734
For a more general way to log out values of pointers or even pointers within structs you can marshal to JSON and log the results.
Here's an example that prints individual pointer & non-pointer values, as well as a struct using this method.
type Line struct {
Point1 *string
Point2 *string
Name string
}
func main() {
point1 := "one"
line := Line{&point1, nil, "fancy"}
printJSON(line.Point1, line.Point2, line.Name)
printJSON(line)
}
func printJSON(i ...interface{}) {
if b, err := json.Marshal(i); err == nil {
log.Println(string(b))
}
}
Upvotes: 2
Reputation: 963
You should probably use if/else in this case BUT if you have many potential "if" conditions for each of point
and point2
you can use Switch statements.
package main
import (
"fmt"
)
func main() {
type Points struct {
Point *string
Point2 *string
}
p := "hi"
pts := Points{nil, &p}
switch pts.Point {
case nil:
fmt.Printf("%v is empty", pts.Point)
default:
fmt.Printf("%v", *pts.Point)
}
fmt.Println()
switch pts.Point2 {
case nil:
fmt.Printf("%v is empty", pts.Point2)
default:
fmt.Printf("%v", *pts.Point2)
}
}
Output:
<nil> is empty
hi
Upvotes: 1
Reputation: 41686
Since there is no ?:
operator in Go, the best way is to write a function:
func StringPtrToString(p *string) string {
if p != nil { return *p }
return "(nil)"
}
Upvotes: 1