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
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)"
}
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