Hi, so i have 3 arrays one of them is empty or not same index as other 2 i want to append that one with empty strings until its of same index which is 2.
package main
import "fmt"
func main() {
arr1 := []string{"apple", "banana", "cherry"}
arr2 := []string{"dog", "cat", "hamster"}
arr3 := []string{}
for _, arr := range [][]string{arr1, arr2, arr3} {
if len(arr) < 1 {
//fmt.Print(arr)
for i := len(arr); i <= 2; i++ {
arr = append(arr, "")
}
}
}
fmt.Print(arr1, arr2, arr3)
}
When i run it the last array is still empty with index 0.
I’ve added some comments to your code below to demonstrate the problem.
package main
import "fmt"
func main() {
arr1 := []string{"apple", "banana", "cherry"}
arr2 := []string{"dog", "cat", "hamster"}
arr3 := []string{}
for _, arr /* this is a copy of one of arr1, arr2, arr3 */ := range [][]string{arr1, arr2, arr3 /* these are the slices by value */} {
if len(arr) < 1 {
//fmt.Print(arr)
for i := len(arr); i <= 2; i++ {
// you're appending and updating the local variable, arr, but not
// reassigning back to arr1, arr2, arr3, etc.
arr = append(arr, "")
}
}
}
fmt.Print(arr1, arr2, arr3)
}
Use the “for i := 0; i < len(array); i++” syntax. It is so good that most programming languages support it. The for range must be used only when needed.
@skillian both your solutions are close, but not exactly what I would do. Simply iterate using the index i, and append to arr[i]