Home > Software engineering >  Use variable out of conditional block in golang
Use variable out of conditional block in golang

Time:09-28

func CheckKafkaReadPartitions(kafkabroker string, topic string, conf config.Config) bool {
    var conn *kafka.Conn

    if conf.TlsEnabled {
        d := &kafka.Dialer{
            TLS: &tls.Config{},
        }
        conn, err := d.Dial("tcp", kafkabroker)
        log.Info("conn is: ", conn)
        log.Info("Using TLS connection")
        if err != nil {
            log.WithError(err).Warn("Kafka broker connection error")
            return false
        }
        defer conn.Close()
    } else {
        conn, err := kafka.Dial("tcp", kafkabroker)
        log.Info("conn is: ", conn)
        log.Info("Using Plaintext connection")
        if err != nil {
            log.WithError(err).Warn("Kafka broker connection error")
            return false
        }
        defer conn.Close()
    }
    log.Info("conn is: ", conn)
    log.Info("Reading Partitions")
    partitions, err := conn.ReadPartitions()
 // SOME OTHER WORK
}

I noticed that when calling ReadPartitions() method, conn is empty even after affecting values to it either in conn, err := kafka.Dial("tcp", kafkabroker) or conn, err := d.Dial("tcp", kafkabroker) What am I missing? Is there any way I could take conn var out of that if/else block without emptying its content?

CodePudding user response:

So basically what happens here is a variable shadowing.

Go has variable scopes, you can have a variable in a global scope by defining it outside of a function. Then you'll be able to use this variable anywhere in the same package (or if it is exported anywhere in your code).

Then you have the variables that are defined in a block of code. Similar to var conn *kafka.Conn you can access this variable from everywhere in the block it was defined (and all the sub-blocks).

Think the blocks as the code that is enclosed by the curly brackets {} This means that the if/else are separate blocks under the func block.

Now what you need to understand is the difference between the = and :=

= is used to assign a value to a variable while := is a shorthand that is used to declare and assign a variable.

So by using conn, err := d.Dial("tcp", kafkabroker) code what you essentially do is declare new variables in the if block and assign the values to them from the returned values of the d.Dial func cal.

There are some cases that you may want to do that. The most common case is when you have a for loop that launches goroutines that uses a variable from an outer block.

  • Related