Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct declarations for slices in Go

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 []?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you all!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading