Home > OS >  Correct declarations for slices in Go
Correct declarations for slices in Go

Time:05-28

I'm following a Go tutorial and I'm a little confused about slice declaration, I learned that slices in Go are declared as an arrays but without a defined length, something like this:

cards := []string{"test1", "test2"}

But, in other example I have a function that returns a type of card (that is an slice of string) and the declaration of the slice change a little bit:

type deck []string

func newDeck() deck {
    cards := deck{} // Why this doesn't have the []?

    cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
    cardValues := []string{"Ace", "two", "three", "four"}

    for _, suit := range cardSuits {
        for _, value := range cardValues {
            cards = append(cards, suit " of " value) // Here comes an error if I put a [] on the declaration
        }
    }

    return cards
}

When I declare cards with [] I cannot use append why? And why is it possible to declare an slice without the []?

Thank you all!

CodePudding user response:

The deck type declaration does use the []:

type deck []string

The composite literal deck{} evaluates to a value of type deck. A deck is a slice type.

The composite literal []deck{} evaluates to a slice of slices. You get a compilation error on the line with append because a string is not a slice type.

  • Related