To add values or elements to a specific index in an array in Go or Golang, you can start by writing the name of the array, then the []
symbol (square brackets), and inside the square brackets, you can specify the index which you need to add the value to. After the brackets, you have to use the =
operator (assignment) followed by the value we need to add to that specific index in that array.
TL;DR
package main
import "fmt"
func main() {
// an array of names
names := [3]string{"John Doe", "Lily Roy", "Daniel Doe"}
// add the value of `Embla Marina` at the
// 1st index of the `names` array
names[1] = "Embla Marina"
// log the contents of the `names` array
fmt.Println(names) // ✅ [John Doe Embla Marina Daniel Doe]
}
For example, let's say we have an array of names like this,
package main
func main(){
// an array of names
names := [3]string{"John Doe", "Lily Roy", "Daniel Doe"}
}
To know more about creating an array, see the blog on How to create a fixed-size array in Go or Golang?
Now we aim to add a new name called Embla Marina
to the names
array at the 1st index
. To do that we can first write the name of the array which is called names
followed by the []
symbol, inside the bracket we can write the index we want to put our name into which is the 1
st index and finally we can use the =
operator followed by the actual value we need to put into it which is the string type value Embla Marina
.
It can be done like this,
package main
func main(){
// an array of names
names := [3]string{"John Doe", "Lily Roy", "Daniel Doe"}
// add the value of `Embla Marina` at the
// 1st index of the `names` array
names[1] = "Embla Marina"
}
Finally, let's log the content inside the names array like this,
package main
import "fmt"
func main() {
// an array of names
names := [3]string{"John Doe", "Lily Roy", "Daniel Doe"}
// add the value of `Embla Marina` at the
// 1st index of the `names` array
names[1] = "Embla Marina"
// log the contents of the `names` array
fmt.Println(names) // ✅ [John Doe Embla Marina Daniel Doe]
}
As you can see that the value of Embla Marina
can be seen in the 1st index of the names
array and the old value of Lily Roy
is overwritten.
See the above code live in The Go Playground.
That's all 😃!
Oldest comments (0)