Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between bool and *bool

Tags:

go

aws-sdk-go

package main

import (
    "fmt"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/route53"
)

func main() {
    sess := session.Must(session.NewSession())
    client := route53.New(sess)
    zones, err := client.ListHostedZones(&route53.ListHostedZonesInput{
        MaxItems: aws.String("100"),
    })
    if err != nil {
        fmt.Printf("Error occurred")
    }
    fmt.Printf("%v", zones)
    if zones.IsTruncated {
        fmt.Printf("%v", zones.NextMarker)
    }
}

The code above fails due to the following condition.

if zones.IsTruncated {
    fmt.Printf("%v", zones.NextMarker)
}

with the result of

non-bool zones.IsTruncated (type *bool) used as if condition

What I want to know is why is there a difference between a regular type(bool) and type(*bool). I understand one is a pointer value however, the condition should still be useful.

Here is a tailed snippet of the output without the condition in place

IsTruncated: true,
MaxItems: "100",
NextMarker: "Wouldn'tYouLikeToKnow"
}
like image 678
Mo Ali Avatar asked Jan 19 '26 17:01

Mo Ali


2 Answers

From standard reference:

"If" statements specify the conditional execution of two branches according to the value of a boolean expression.

So, to answer your question, if statements explicitly require boolean expressions. *bool is still not bool. You need to explicitly dereference the pointer (which could even be nil in which case your program will panic).

Here's how you would re-write your if statement:

if *zones.IsTruncated {
    fmt.Printf("%v", zones.NextMarker)
}

but make sure it is not nil

like image 133
wingerse Avatar answered Jan 22 '26 07:01

wingerse


You need to dereference to a struct. You need to use the := operator to do so. Something like -

new_struct := *your_pointer

You would then use the new_struct instead.

like image 39
BryceH Avatar answered Jan 22 '26 09:01

BryceH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!