The Grow() method

Report a typo

Below you will see a small program that uses the Grow() function to preallocate the size of the buffer slice:

package main

import (
    "fmt"
    "strings"
)

func main() {
    var b strings.Builder
    b.Grow(?)

    b.WriteString("Player list:\n")
    for i := 1; i < 5; i++ {
        b.WriteString(fmt.Sprintf("Player %d\n", i))
    }

    fmt.Print(b.String())
}

// Output:
// Player list:
// Player 1
// Player 2
// Player 3
// Player 4

Please enter below an integer number we should pass to the Grow() method with the exact capacity or an estimated capacity to preallocate the size of the buffer slice required to store the string the program needs to build.

Enter a number
___

Create a free account to access the full topic