IsharM
IsharM

Reputation: 153

How do i initialize a slice for future assignment?

greetslice := []string{
        "Hello, %v. Welcome to the world!",
        "Come on %v Explore.",
        "You are very welcome here %v!",
    }

What if I want to do it this way...

var greetslice []string

greetslice = {
    "Hello, %v. Welcome to the world!",
    "Come on %v Explore.",
    "You are very welcome here %v!",
}

But the following error occurs.

# greetings
../greetings/greetings.go:29:15: syntax error: unexpected {, expecting expression
../greetings/greetings.go:35:2: syntax error: non-declaration statement outside function body

How do I initialize the slice first and assign it some values later correctly?

Upvotes: 1

Views: 56

Answers (1)

icza
icza

Reputation: 417662

This assignment:

greetslice = {
    "Hello, %v. Welcome to the world!",
    "Come on %v Explore.",
    "You are very welcome here %v!",
}

Is invalid. The composite literal must include the type:

greetslice = []string{
    "Hello, %v. Welcome to the world!",
    "Come on %v Explore.",
    "You are very welcome here %v!",
}

Try this one on the Go Playground.

Another option is to use the builtin append() function to append values to a slice which may even be nil:

greetslice = append(greetslice,
    "Hello, %v. Welcome to the world!",
    "Come on %v Explore.",
    "You are very welcome here %v!",
)

Try this one on the Go Playground.

Also note that if you know how many elements you will add, you can initialize your slice with 0 length and sufficient capacity, which may speed up the further append operations:

var greetslice = make([]string, 0, 3) // room for 3 elements to append later

Upvotes: 4

Related Questions