Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log the value of a pointer if it is not nil, otherwise log nil in GO?

Tags:

go

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

like image 958
Said Saifi Avatar asked Nov 03 '16 16:11

Said Saifi


1 Answers

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)"
}
like image 177
Roland Illig Avatar answered Sep 20 '22 18:09

Roland Illig