gordonklaus / ineffassign

Detect ineffectual assignments in Go code.
MIT License
394 stars 22 forks source link

Why this situation report ineffassign? #33

Closed xiekeyi98 closed 5 years ago

xiekeyi98 commented 5 years ago

I have codes like this

    format = skipWhiteSpace(format)
    for token, formatRemain, succ := getFormatToken(format); len(token) != 0; format = formatRemain {
        if !succ {
            isDuration, isDate = false, false
            break
        }
        if _, ok := durationTokens[token]; ok {
            isDuration = true
        } else if _, ok := dateTokens[token]; ok {
            isDate = true
        }
        if isDuration && isDate {
            break
        }
        token, formatRemain, succ = getFormatToken(format)
    }
    return
}

And ineffassign tell me No.2 line warning: ineffectual assignment to formatRemain. But I think this variable I have already used.

I was wondering if you could tell me what I have done wrong?

gordonklaus commented 5 years ago

When you use formatRemain in the Post statement of the for-loop (format = formatRemain), it takes its value from the last line of the for-loop, because the Post statement is only run after the loop body (and condition). The value assigned to formatRemain in the Init statement of the for-loop is never used.

I think the bug in your program is on the last line of the for-loop, which should read:

token, formatRemain, succ = getFormatToken(formatRemain)

and you should remove the Post statement from the loop.

Or, alternatively:

    format = skipWhiteSpace(format)
    for {
        var token string
        var succ bool
        token, format, succ = getFormatToken(format)
        if len(token) == 0 {
            break
        }
        if !succ {
            isDuration, isDate = false, false
            break
        }
        if _, ok := durationTokens[token]; ok {
            isDuration = true
        } else if _, ok := dateTokens[token]; ok {
            isDate = true
        }
        if isDuration && isDate {
            break
        }
    }
    return
xiekeyi98 commented 5 years ago

@gordonklaus
I truly appreciate your timely help. I am sorry for taking up your time.

Thanks a lot.

gordonklaus commented 5 years ago

No problem :)