Unknow error received when binding value to a string

Hi everyone,
I have a case, that makes me confused , and don’t understand the problem.

var company_code string = ""
	if model.CompanyCode == "" {
		logger.Infof("GetDevices 1 (%s)", company_code) // print empty string
		company_code, err := utilities.GetStringValue(ctx, constants.CompanyCode)
		test := company_code
		logger.Infof("GetDevices  test (%v)", test) // print "test_code"

		if err != nil {
			logger.Errorf("Cannot get company_code")
		logger.Infof("GetDevices  company_code (%v)", company_code) // print "test_code"
		model.CompanyCode = company_code
	} else {
                model.CompanyCode = "hello_falling_back"
	logger.Infof("CompanyCode: (%v)", company_code) // print empty ????? why????
	logger.Infof("model.CompanyCode: (%v)", model.CompanyCode)` // print "test_code"

As you use := within the ifs block, you create a new variable shadowing the outer company_code, which gets out of scope once the block is left.

You can solve your problem by also pre-declaring err and then using = for the assignment instead.


just to add that if you use a linter, maybe integrated in your IDE, it will help you to avoid such kind of problems

1 Like

thank you, that’s makesense now.

thank you, I will try to install one.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.