Determining the Ambiguous Golang Error

I'm new to golang and came across this:

err := ipdf.Open(source)
if err != nil {
    panic("Couldn't open pdf.")
}

payload, err := ioutil.ReadFile(other)
if err != nil {
    panic("Couldn't read other file.")
}

      

why am I allowed to define the err variable a second time ?

+3


source to share


3 answers


Unlike regular variable declarations, a short variable declaration can update variables if they were originally declared earlier in the same block (or a parameter list if the block is the body of a function) with the same type, and at least one of the -blank variables are new ... As a consequence, an override can only appear in a short multi-variable declaration. The Redeclaration does not introduce a new variable; it just assigns a new value to the original.



https://golang.org/ref/spec#Short_variable_declarations

+5


source


Short variable declarations are used mainly when you need to declare variables for temporary use, and these variable names can be used in further programs. For example, "err" can be used at any time in a later program. Suppose the language was java, you would have to declare more different variable names for the further program. But in golang, short variable declarations work like "let" in javascript. Hope this helps.



0


source


I would recommend using the inline checks as much as possible:

// local scope
if err := ipdf.Open(source); err != nil {
    panic("Couldn't open pdf.")
}

payload, err := ioutil.ReadFile(other)
if err != nil {
    panic("Couldn't read other file.")
}

      

0


source







All Articles