0

I am new to Golang. I am confused why I got the error that partial is not used in the code below?

// Using var keyword
var partial string

for i, request := range requestVec {
    if i == (len(requestVec)-1) && !strings.Contains(request, "\r\n\r\n") {
        partial = request
        break
    }
}

I assign request to partial in the if statement.

Jem Tucker
  • 1,143
  • 16
  • 35
xiaokang lin
  • 153
  • 1
  • 10
  • 4
    But you do nothing with it....what's the point of assigning it if you won't use it later? – de3 Nov 02 '20 at 23:10
  • I see. Is that what the error about? – xiaokang lin Nov 02 '20 at 23:24
  • 2
    It is an error to declare a variable without using it. You do not use `partial`, therefor you get this error. – JimB Nov 02 '20 at 23:30
  • Does this answer your question? [How to avoid annoying error "declared and not used"](https://stackoverflow.com/questions/21743841/how-to-avoid-annoying-error-declared-and-not-used) –  Nov 04 '20 at 10:24

1 Answers1

1

It is a compiler error in Go to declare a variable without using it.

In the code in you're example the variable partial is never used, only assigned, so is seen as unused. If you added additional code that read the variable then the error would be resolved. For example

var partial string

for i, request := range requestVec {
    if i == (len(requestVec)-1) && !strings.Contains(request, "\r\n\r\n") {
        partial = request
        break
    }
}

fmt.Println(partial) // We are now using `partial`
Jem Tucker
  • 1,143
  • 16
  • 35