9

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

5
  • Out of curiosity, what could be more simple than an if/else statement? It may be different in other languages, but in Go if/else is perfectly idiomatic. Commented Nov 3, 2016 at 19:03
  • @SamWhited in this case its simple but I am not asking this question specifically for this case, I am asking this question for the case when you have a structure containing fields that are pointers and you want to log them instead logging their addresses Commented Nov 4, 2016 at 7:21
  • maybe I'm still misunderstanding then; I don't understand why this would be any different with more pointers or structs. Are you just wanting a different syntax for if/else like the ternary operator (?:) suggested in one of the answers? Commented Nov 4, 2016 at 14:27
  • @SamWhited no, what I need is to be able to create a method or to use some library that have a method that takes any structure and loops into its elements and log/print them; Commented Nov 4, 2016 at 15:55
  • Ah, I see, thank you; that was not at all clear to me from the example (which doesn't even contain a struct) or the text; maybe you could the example and phrase it how you did in that comment? It would be much clearer. Commented Nov 4, 2016 at 16:37

4 Answers 4

2

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

Go Playground

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

in this case its simple but I am not asking this question specifically for this case, I am asking this question for the case when you have a structure containing fields that are pointers and you want to log them instead logging their addresses so if I want to use some method it should loop over all elements of any structure
1

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

Go playground

4 Comments

in this case it's simple but I am not asking this question specifically for this case, I am asking this question for the case when you have a structure containing fields that are pointers and you want to log them instead logging their addresses
It wasn't clear in your original post that you were looking for examples of pointers inside a struct. In any case, I edited my answer with the variables in a struct. It works the same way.
thank you but when I meant structure I meant any structure so I can create a method or something that takes any structure and loops on the structure elements and log them. But I will upvote your answer thank you
@user6638204 Do you mean putting multiple instances of a struct as I suggested above into a dynamic array (slice) and writing a function that loops (ranges) through it printing the contents?
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.