Tam
Tam

Reputation: 35

How to assign a value to the first index of an empty slice in Golang?

I wrote this code but I have panic runtime problem:

func climbingLeaderboard(scores, alice []int32) []int32 {
  var rank, rankalice []int32
  rank[0] = 1
}

Can you tell me where the problem is?

Thank you in advance

Upvotes: 0

Views: 1216

Answers (2)

Orkhan Zeynalli
Orkhan Zeynalli

Reputation: 144

After creating a slice you need to use append() to add an element to it:

func climbingLeaderboard(scores []int32, alice []int32) []int32 {
   var rank []int32 = []int32{}
   rank = append(rank, 1) // rank[0]  is  1
}

Upvotes: 1

Eklavya
Eklavya

Reputation: 18420

rank is an empty slice. Using append you can add an element

var rank []int32        // Create empty slice
rank = append(rank, 1)

Or

Using make creates a slice of a specific length and access rank[0] to set value.

rank := make([]int32, 5)  // Create slice of length 5
rank[0] = 1

Demo code in the playground here

Upvotes: 2

Related Questions