DEV Community

Discussion on: Go - Safe truncate string

Collapse
 
takakd profile image
Takahiro Kudo

Thank you for your feedback. I cannot notice my mistake. Could you give me any test cases?

Collapse
 
jgreen01su profile image
jgreen01su

Hi Takahiro. Shiming isn't exactly right. I don't see any bugs with your code vs his. But he's still half right, I'll explain why.

    ...
    count := 0
    for _, char := range str {
    truncated += string(char)
        count++  // <-- shiming is talking about this
        if count >= length {
            break
        }
        /* Someone may mistakenly put code here that uses
         * count forgetting that count was incremented for
         * the next loop iteration. */
    }
    ...
Enter fullscreen mode Exit fullscreen mode

While your code works, in general it's not good practice to increment your counter before the end of the loop. It would be very easy for someone to make a mistake modifying this code.

Better would be this:

    ...
    count := 0
    for _, char := range str {
        if count >= length {
            break
        }
        truncated += string(char)
        count++
    }
    ...
Enter fullscreen mode Exit fullscreen mode

But best is exactly the code @huahuayu wrote because he's using the built-in for loop counter. He doesn't even need to worry about initializing and incrementing the counter because the for loop does all the hard work for him.

In general, the less code the better.

Thread Thread
 
takakd profile image
Takahiro Kudo

Thank you for your explaining. I have made sense. 😆