Search code examples
gocompiler-errorsappendunused-variables

Why an "unused variable" compilation error when ignoring the result of append?


why if we append data in slice and not use it (variable mySlice in the program), why not throw the error message "unused variable" golang. Thankyou

#example

 var mySlice []string

 mySlice = append(mySlice,"halo")

and same behaviour with map

#example

var my = map[string]int{}

my["tes"]=1

Solution

  • Spec: Variable declarations:

    Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.

    As you can see, a compiler may or may not accept unused variables. The current Go compiler implements this by checking if the variable is read. Reading a variable means the variable is used.

    The "unused variable" (or rather "declared but not used") is given by the compiler if you don't read a variable.

    For example:

    var i int
    i = 3
    

    Even though you are assigning a value to i in the above example, since it is not read, this is a compile-time error.

    Appending to a slice using append() involves reading the slice (the slice is passed to append()).

    Assigning a value to a map key involves reading the map value.

    Same goes if you don't use append() but "directly" assign a value to a slice element:

    var i = []int{0}
    i[0] = 1
    

    This is OK because assigning to i[0] involves reading the slice header to determine the (address of the) element to which we're assigning.

    But if we were to assign to i itself like this:

    var i = []int{0}
    i = []int{1}
    

    This assignment doesn't involve reading i so it is also a compile-time error.

    If we were to use a struct for example:

    type Point struct{ x, y int }
    
    var p Point
    p.x = 1
    

    This still compiles, even though the assignment doesn't really involve reading the p struct. We might think of it as "identifying" the p.x field involves accessing the p variable.

    This is a little bit of "gray area" and is based on opinion of the Go authors, but this is how they decided and implemented it.